正则表达式'(?<=#)[^#] +(?=#)'如何工作?

我在C#程序中具有以下正则表达式,并且难以理解它:


(?<=#)[^#]+(?=#)

我将其分解为我认为的理解:


(?<=#)    a group, matching a hash. what's `?<=`?

[^#]+     one or more non-hashes (used to achieve non-greediness)

(?=#)     another group, matching a hash. what's the `?=`?

因此,我遇到的问题是?<=and ?<部分。从阅读MSDN开始,?<name>它用于命名组,但是在这种情况下,尖括号永远不会关闭。


我?=在文档中找不到,搜索起来真的很困难,因为搜索引擎通常会忽略那些特殊字符。


扬帆大鱼
浏览 3564回答 3
3回答

料青山看我应如是

正如另一位发帖人所述,这些是环视功能,是用于更改匹配内容和时间的特殊构造。这说:(?<=#)&nbsp; &nbsp; match but don't capture, the string `#`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; when followed by the next expression[^#]+&nbsp; &nbsp; &nbsp;one or more characters that are not `#`, and(?=#)&nbsp; &nbsp; &nbsp;match but don't capture, the string `#`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; when preceded by the last expression因此,这将匹配两个#s 之间的所有字符。在许多情况下,先行和后退非常有用。例如,考虑规则“匹配所有b后跟一个” a。您的第一次尝试可能类似于b[^a],但那是不对的:这也将与buin bus或boin相匹配boy,但是您只想使用in b。而且它不会匹配bin cab,即使它后面没有一个a,因为也没有匹配的字符了。要正确执行此操作,您需要先行执行:b(?!a)。这表示“匹配一个,b但a之后不匹配,也不要成为匹配的一部分”。因此,它将仅匹配bin bolo,这就是您想要的;同样,它将与bin 匹配cab。
打开App,查看更多内容
随时随地看视频慕课网APP