简体   繁体   中英

Greater Than and Less Than Symbols in C# Regular Expression

I am using a Regex pattern "MilliSeconds\\s\\&lt;" and try to compare with the input "MilliSeconds <" but everytime my Regex match is getting failed. Can anyone tell what is wrong here?

MilliSeconds followed by backslash and &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; does not stand both for a &lt; string and < character. In other words, these entities are not identical for the regex engine.

It appears you can modify the pattern . Note that it is possible to match either < or &lt; with the help of alternation and grouping :

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

So, (?:&lt;|<) is a non-capturing group that tries to match &lt; and if it is not found, < is tried.

Use simply 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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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