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

Regex 正则表达式在指定距离内匹配具有指定单词的句子,regex,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\

如何将一个句子与距离为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

请尝试以下正则表达式:

^Bacon(\s\w+)?(\s\w+)?\smeat$
你可以现场观看

其中:

Bacon is thinly sliced lean pork meat
Bacon is meat
Bacon is pork meat
Bacon meat
Bacon is not a meat
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
编辑:

这可以缩短为(实时):

其中,
{0,2}
表示0到2次之间。更改为
{0,3}
意味着
培根不是肉
也会匹配

编辑2:

要匹配
(可选逗号),(请现场查看):

其中:

Bacon is thinly sliced lean pork meat
Bacon is meat
Bacon is pork meat
Bacon meat
Bacon is not a meat
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

请尝试以下正则表达式:

^Bacon(\s\w+)?(\s\w+)?\smeat$
你可以现场观看

其中:

Bacon is thinly sliced lean pork meat
Bacon is meat
Bacon is pork meat
Bacon meat
Bacon is not a meat
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
编辑:

这可以缩短为(实时):

其中,
{0,2}
表示0到2次之间。更改为
{0,3}
意味着
培根不是肉
也会匹配

编辑2:

要匹配
(可选逗号),(请现场查看):

其中:

Bacon is thinly sliced lean pork meat
Bacon is meat
Bacon is pork meat
Bacon meat
Bacon is not a meat
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
这应该行得通

^.*\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
这应该行得通

^.*\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

请问如何匹配“培根,是肉吗?”@YoongKangLim如中所示,您想匹配
培根,是肉,同时仍然匹配当前所有的-逗号是可选的?逗号是可选的谢谢您的帮助我可以问如何匹配“培根,是肉”@YoongKangLim如中所示,您想匹配
培根,是肉
,虽然仍然匹配所有当前的逗号-逗号是可选的?逗号是可选的谢谢您的帮助