如何非贪婪地进行多个后向匹配
Source: <prefix><content1><suffix1><prefix><content2><suffix2>
Engine: PCRE
RegEx1: (?<=<prefix>)(.*)(?=<suffix1>)
RegEx2: (?<=<prefix>)(.*)(?=<suffix2>)
Result1: <content1>
Result2: <content1><suffix1><prefix><content2>
RegEx2 所需的结果只是
[我希望我已经从 NoteTab 语法正确翻译了这个。 我不做 很多正则表达式编码。 <前缀>、<内容> & <后缀> 术语只是用来表示任意字符串。 只有“<” 在“?<=lookbehind命令中很重要。]
我怀疑这很简单,但经过太多小时的搜索后我发现 放弃自己解决。
帮助
感谢艺术的
Source: <prefix><content1><suffix1><prefix><content2><suffix2>
Engine: PCRE
RegEx1: (?<=<prefix>)(.*)(?=<suffix1>)
RegEx2: (?<=<prefix>)(.*)(?=<suffix2>)
Result1: <content1>
Result2: <content1><suffix1><prefix><content2>
The desired result for RegEx2 is just <content2> but it is obviously greedy.
How do I make RegEx2 non-greedy and use only the last matching lookbehind?
[I hope I have translated this correctly from the NoteTab syntax. I don't do
much RegEx coding. The <prefix>, <content> & <suffix> terms are just meant to represent arbitrary strings. Only the "<" in the "?<=" lookbehind command is significant.]
I suspect it is something simple but after too many hours of searching I'm
giving up on solving it myself.
Thanks for the help
Art
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您使用:
这可以确保匹配中没有
。 完整的匹配结果将是I suggest you use:
This makes sure that there can be no
<prefix>
inside the match. The complete match result will be<content2>
前面放个贪心的东西?
由于贪婪的
(?:.*)
将尽可能多地吞噬,因此只有最小值才会与模式的其余部分匹配 - 有效地使其余部分变得非贪婪。非贪婪的
.*?
也可能有效:Put something greedy in front of it?
Since the greedy
(?:.*)
will gobble as much as it can, only the minimum will be matched by the rest of the pattern - effectively making the rest non-greedy.The non-greedy
.*?
might also work:我刚刚遇到了同样的问题。 但就我而言,
这就是我想要的。
此表达式将匹配< /代码>。 (我想是的。我不太擅长正则表达式。)
和
之间的任何字符串联,并且不包含子字符串I just had the same problem. But in my case it was
That did what I wanted.
This expression will match anything that is a concatenation of characters between
<prefix>
and<suffix>
and doesn't contain the substring<prefix>
. (I think so. I'm not very good at regexp.)