简体   繁体   English

正则表达式代码说明

[英]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. (?<=<Last>)是断言的外观。 that means it matches .* only if there is a <Last> in front 这意味着它匹配.*仅在前面有<Last>

(?=</Last>) is a look ahead assertion. (?=</Last>)是一个前瞻性断言。 ensures that there is a <\\Last> following on .* 确保在.*之后有一个<\\Last> .*

More information about regex in .net can be found here on msdn . 可以在msdn上找到有关.net中正则表达式的更多信息。

Annotation, the provided example isn't a complete line of code ( See Class Regex on msdn ) 注释,提供的示例不是完整的代码行( 请参阅msdn上的Class Regex

This should be a part of something like this: 这应该是这样的一部分:

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

that creates a new Regex object. 创建一个新的Regex对象。

Another possibility is to use regexes without creating regex objects, would look like this with the static method isMatch : 另一种可能性是使用正则表达式而不创建正则表达式对象,静态方法isMatch看起来像这样:

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

This returns true or false. 这返回true或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 . 如前所述,模式(?<=<Last>).*(?=</Last>)匹配最长的文本字符串,其后跟<Last></Last> ,并带有正向周围

Note however, that due to the greediness , this matched string itself can also contain <Last> and/or </Last> 但是请注意,由于贪婪 ,此匹配的字符串本身也可以包含<Last>和/或</Last>

It's basically looking for the <Last> tags in some xml document including its contents. 它基本上是在某些xml文档(包括其内容)中寻找<Last>标签。

?<= is a look behind assertion. ?<=是断言的外观。 See here for a thorough explanation. 请参阅此处以获取详细说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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