简体   繁体   中英

Regex code explanation

Can someone tell me what this line of code means, I know that it looks for regular expressions but i dont understand the bit at the end.

System.Text.RegularExpressions.Regex("(?<=<Last>).*(?=</Last>)");

Thanks in advance.

(?<=<Last>) is a look behind assertion. that means it matches .* only if there is a <Last> in front

(?=</Last>) is a look ahead assertion. ensures that there is a <\\Last> following on .*

More information about regex in .net can be found here on msdn .

Annotation, the provided example isn't a complete line of code ( See Class Regex on msdn )

This should be a part of something like this:

Regex MyRegex = new System.Text.RegularExpressions.Regex("(?<=<Last>).*(?=</Last>)");

that creates a new Regex object.

Another possibility is to use regexes without creating regex objects, would look like this with the static method isMatch :

System.Text.RegularExpressions.Regex.IsMatch(StringToSearchIn, "(?<=<Last>).*(?=</Last>)")

This returns true or false.

As noted before, the pattern (?<=<Last>).*(?=</Last>) matches the longest string of text preceded by <Last> and followed by </Last> , expressed with the positive lookarounds .

Note however, that due to the greediness , this matched string itself can also contain <Last> and/or </Last>

It's basically looking for the <Last> tags in some xml document including its contents.

?<= is a look behind assertion. See here for a thorough explanation.

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