[英]How to exclude word from matching that is optional using regex
I want to be able to match the following:我希望能够匹配以下内容:
top of pole
top of existing pole
existing top of pole
but not但不是
proposed top of pole
I tried to use ((?=proposed)\s)*top\sof\s(existing\s)?pole
with look back, but it doesn't quite work, still matching proposed
top of pole.我尝试使用
((?=proposed)\s)*top\sof\s(existing\s)?pole
回顾一下,但它不太有效,仍然匹配proposed
的极点顶部。
How to exclude certain word when it is optional?可选时如何排除某些单词?
You can exclude a certain word like this:您可以像这样排除某个单词:
(\w+\s(?<!proposed\s))?top\sof\s(existing\s)?hole
There are a couple of things going on in this solution:此解决方案中有几件事:
\w+\s
matches a word and 1 whitespace character, \w+\s
匹配一个单词和 1 个空格字符,
The negative lookbehind (?<!proposed\s)
gurantees that, once the regex is at this position after the word and space, looking backwards we do not match "proposed ".否定的后视
(?<!proposed\s)
保证,一旦正则表达式在单词和空格之后的这个 position 处,向后看我们不匹配“proposed”。
The (...)?
(...)?
makes the (word, space, and no "proposed ") match optional.使 (word, space, and no "proposed ") 匹配可选。
For a more detailed walkthrough: https://regex101.com/r/LLs2zA/1有关更详细的演练: https://regex101.com/r/LLs2zA/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.