正则表达式匹配指定距离内具有指定单词的句子

时间:2017-03-18 06:39:11

标签: regex

如何将一个句子与培根和肉匹配,距离为2或小于2个字?

Bacon is thinly sliced lean pork meat ----Reject

Bacon is pork meat    ----Match

我试过了:

^(\bBacon\b)(\040){1,2}(\bmeat\b)$   => i try to match with the "space" between but it's not working
^(?=.*?\bBacon\b)(?=.*?\bmeat\b).*$  => this will match everything in between regardless the distance

2 个答案:

答案 0 :(得分:2)

尝试以下正则表达式:

^Bacon(\s\w+)?(\s\w+)?\smeat$

你可以看到这个here

其中:

Bacon is thinly sliced lean pork meat
Bacon is meat
Bacon is pork meat
Bacon meat
Bacon is not a meat

它找到了这些:

Bacon is meat
Bacon is pork meat
Bacon meat

修改

这可以缩短为(实时here):

^Bacon(\s\w+){0,2}\smeat$

{0,2}表示0到2次之间。更改为{0,3}意味着Bacon is not a meat也会匹配。

编辑2:

要匹配,(可选逗号),(现场直播here):

^Bacon\,?(\s\w+){0,2}\smeat$

其中:

Bacon is thinly sliced lean pork meat
Bacon is meat
Bacon is pork meat
Bacon meat
Bacon, is meat
Bacon, is pork meat
Bacon, meat
Bacon, is not a meat
Bacon is not a meat
Bacon
Bacon is

匹配:

Bacon is meat
Bacon is pork meat
Bacon meat
Bacon, is meat
Bacon, is pork meat
Bacon, meat

答案 1 :(得分:1)

这应该有用。

^.*\bBacon\b\s(\w+\s){0,2}\bmeat\b.*$

Bacon is pork meat  --match
Bacon is thinly sliced lean pork meat  --reject
Bacon meat  --match
Bacon is meat  --match
Bacon is tasty meat  --match
Bacon is not tasty meat  --reject