简体   繁体   English

C#正则表达式中的大于和小于符号

[英]Greater Than and Less Than Symbols in C# Regular Expression

I am using a Regex pattern "MilliSeconds\\s\\&lt;" 我正在使用正则表达式模式"MilliSeconds\\s\\&lt;" 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 &lt; MilliSeconds后跟反斜杠和&lt;

string value = @"MilliSecs <Test Run";
string pattern = @"MilliSecs\s\&lt;";

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 &lt; 注意,正则表达式引擎不知道XML转义的字符串,并且&lt; does not stand both for a &lt; 不能同时代表&lt; 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 &lt; 请注意,可以匹配<&lt; with the help of alternation and grouping : 交替分组的帮助下:

@"MilliSeconds\s(?:&lt;|<)"
                ^^^^^^^^^^

So, (?:&lt;|<) is a non-capturing group that tries to match &lt; 因此, (?:&lt;|<)是试图与&lt;匹配的非捕获组&lt; 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM