[英]Greater Than and Less Than Symbols in C# Regular Expression
I am using a Regex pattern "MilliSeconds\\s\\<"
我正在使用正则表达式模式
"MilliSeconds\\s\\<"
and try to compare with the input "MilliSeconds <"
but everytime my Regex match is getting failed. 并尝试与输入
"MilliSeconds <"
进行比较,但是每次我的Regex匹配失败时。 Can anyone tell what is wrong here? 谁能告诉我这是怎么回事?
MilliSeconds followed by backslash and <
MilliSeconds后跟反斜杠和
<
string value = @"MilliSecs <Test Run";
string pattern = @"MilliSecs\s\<";
Match mtchObj = Regex.Match(value,pattern);
if(mtchObj.Success)
{
MessageBox.Show("Matched");
}
Which my input string is not getting matched with the pattern? 我的哪个输入字符串没有与模式匹配?
Note that the regex engine does not know of XML escaped strings, and <
注意,正则表达式引擎不知道XML转义的字符串,并且
<
does not stand both for a <
不能同时代表
<
string and <
character. 字符串和
<
字符。 In other words, these entities are not identical for the regex engine. 换句话说,这些实体对于正则表达式引擎而言并不相同。
It appears you can modify the pattern
. 看来您可以修改
pattern
。 Note that it is possible to match either <
or <
请注意,可以匹配
<
或<
with the help of alternation and grouping : 在交替和分组的帮助下:
@"MilliSeconds\s(?:<|<)"
^^^^^^^^^^
So, (?:<|<)
is a non-capturing group that tries to match <
因此,
(?:<|<)
是试图与<
匹配的非捕获组<
and if it is not found, <
is tried. 如果找不到,则尝试
<
。
Use simply string pattern = @"MilliSecs\\s<";
使用简单的
string pattern = @"MilliSecs\\s<";
, there is no need to escape <
in this regex since it doesn't have a special meaning. ,由于它没有特殊含义,因此无需在此正则表达式中转义
<
。 You code should be: 您的代码应为:
string value = @"MilliSecs <Test Run";
string pattern = @"MilliSecs\s<";
Match mtchObj = Regex.Match(value,pattern);
if(mtchObj.Success)
{
MessageBox.Show("Matched");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.