【发布时间】:2020-07-23 02:24:50
【问题描述】:
问题:如何在模式匹配特定单词(查找单词)的同时忽略其中任何位置包含子字符串(单词 Exclude)的任何字符串?
我想要做的是找到所有包含单词 Find 的模式,并排除任何包含 Exclude 字符串中任何位置的模式。
我对模式匹配的期望是:
Find - Succeed
ExcludeFind - Fail
FineExclude - Fail
xxxFind - Succeed
Findxxx - Succeed
xxxFindxxx - Succeed
ExcludexxxxxxxxxxFind - Fail
FindxxxxxxxxxxExclude - Fail
ExcludexxxxxxxxxxFindxxxxxxxxxxExclude - Fail
我制作的正则表达式模式,其结果各不相同:
(\bFind\b) - Only works if Find is the only word
(\w?Find\w?) - Pattern matches any word with Find
((\w?Find\w?)([^Exclude])|([^Exclude])(\w?Find\w?)) - Image below
浏览了各种 Stack 帖子,我尝试了一种更复杂的方法,即正面和负面的lookbehinds,但它在任何模式上都没有成功。
(?<!Exclude)(Find)(?<=Exclude)
如果是(?<!Exclude)(Find),那么这可行,但仅有的两个问题ExcludexxxxxxxxxxFind 和FindxxxxxxxxxxExclude 也成功了,我不希望这样,因为这些字符串包含“排除”字样。
我认为通配符变体可能会起作用 (?<!Exclude)?(Find) 或类似的东西,但同样,没有模式匹配这种情况。
【问题讨论】:
-
基本问题:它必须是一个正则表达式吗?如果您使用的是编程语言,使用不同的方法可能会更容易。
-
顺便说一句,检查您的第三条测试行是否显示
Fine而不是Find。
标签: regex