开发者

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>).*(?开发者_如何学Python=</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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜