【发布时间】:2020-09-01 08:05:11
【问题描述】:
我需要一个匹配单词的正则表达式,无论顺序如何。例如,这些行应该与标记的范围相匹配,
A longword1 B longword2 C
^-------------------^
A longword2 B longword1 C
^-------------------^
虽然这些不应该:
A longword1 B longword1 C
A longword2 B longword2 C
A longword1 B
A longword2 C
(A、B、C 是填充符,基本上可以是任何文本)
可以只使用替换,例如:\b((longword1).*?(longword2)|(longword2).*?(longword2))\b。但是正则表达式会阶乘增长,即三个单词需要 3!替补。也可以使用子程序,例如\b((?'A'longword1).*?(?'B'longword2')|(?P>B).*?(?P>A))\b。虽然更短,但我仍然需要包含它的所有排列。
现在我已经阅读了this post 和this other one,但接受的答案并不能完全解决我的问题。使用\b(?=.*longword1)(?=.*longword2).*\b 将匹配整行而不是我显示的范围。
我明白,如果我对照单词列表检查句子会容易得多。但是我当前的用例阻止了它的实现;我只能使用正则表达式。
这里有一些链接来说明我的意思:
预期:
- 使用替代品:https://regexr.com/5b6pv
- 使用子程序:https://regexr.com/5b6ss
不正确:
- 使用正向前瞻(如链接):https://regexr.com/5b6q2
有没有更简单的正则表达式来解决这个问题?
【问题讨论】:
-
将
A和C放在其他帖子中的解决方案周围。 -
@Barmar 我找不到您提到的解决方案。什么意思?
-
A.*\b(?=.*longword1)(?=.*longword2).*\b.*C -
@Barmar 但它匹配从
A到C。 OP 只需要匹配从 word1 到 word2 的子字符串。A和C只是填充物,它们表示任何文本。并且单词 1 和单词 2 可以互换。而且可以有两个以上的词。