【发布时间】:2013-05-30 19:03:23
【问题描述】:
我有一个存储用户输入的字符串数组,我想检查输入用户是否仅包含特定单词END,我不介意单词之前是否有空格或例如,在单词之后,用户可以输入诸如END 或“END”或“END”或“END”之类的单词。我真的不在乎单词之前或之后有多少空格,我只想检查输入字符串是否仅包含单词 END 而不考虑空格。
我试过了
Regex regex_ending_char = new Regex(@"^END|^\s+END$|^END+\s$");
// to compare the word "END" only nothing before it nor after it -
// space is of anywhere before or after the word
Match Char_Instruction_match = regex_ending_char.Match(Instruction_Separator[0]);
if (!Char_Instruction_match.Success) // True if word doesn't end with "END"
{
richTextBox2.Text += "Error in line " + (LineNumber + 1) + ", Code must end with 'END'" + Environment.NewLine;
}`
我也试过了
Regex regex_ending_char = new Regex(@"^END|^\s+END$|^END+\s$");
// to compare the word "END" only nothing before it nor after
// it - space is of anywhere before or after the word
Regex.Replace(Instruction_Separator[0], @"\s+", "");
Match Char_Instruction_match = regex_ending_char.Match(Instruction_Separator[0]);
if (!Char_Instruction_match.Success) // True if word doesn't end with "END"
{
richTextBox2.Text += "Error in line " + (LineNumber + 1) + ", Code must end with 'END'" + Environment.NewLine;
}`
问题是我必须只检查数组Instruction_Separator[0] 的第一个元素,而不是任何其他元素。因此,如果用户在单词END 之前输入一个空格,例如“END”,那么Instruction_Separator 数组将变为Instruction_Separator[0] = " ", Instruction_Separator[1] = END,因此即使用户输入了正确的字符串,他也只输入了一个开头的空格,如果单词前后有空格,我没有问题。
感谢大家的回复,我尊重您的所有回答。我要做的是构建一个汇编程序,我必须检查语法错误,并且用户输入中的 cmets 是可以的。例如,如果用户输入如下:
ORG 100 //Begin at memory location 100
LDA A // Load A
A, DEC 83 // A has a decimal value of 83
END // End the code
那么没有任何语法错误,我可以给出结果。
另外,如果用户在每行之前添加空格,那也没关系
ORG 100 //Begin at memory location 100
LDA A // Load A
A, DEC 83 // A has a decimal value of 83
END // End the code
所以我想检查每一行是否包含正确的语法,并且我并不关心每行的正确格式之前或之后的任何空格。
用户语法错误类似于:
OR G 100 //Begin at memory location 100
LDA A // Load A
A, DEC 83 // A has a decimal value of 83
EN To end the code
注意ORG写成“OR G”是错误的,END也写成“EN”,用户忘记在“结束代码”注释前放置“//”
所以我需要做的是检查最后一行是否包含单词“END”,如果有“//”,那么它后面的内容是注释。但是如果用户想在一行中添加注释,他必须输入“//”。如果他不想添加评论,那不是必须的。任何想法我如何使用正则表达式来做到这一点,正如我上面提到的,我尝试了Regex regex_ending_char = new Regex(@"^END|^\s+END$|^END+\s$");,但我似乎没有正确工作
提前感谢您的回复。
【问题讨论】: