2017-03-18 130 views
0

如何搭配培根的一句話和肉的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

試試下面的正則表達式:

^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 
+0

你的答案工作太好了,謝謝! –

+0

請問如何匹配「培根,是肉」? –

+0

@YoongKangLim如,要匹配'培根,是meat',而目前所有的那些仍然匹配 - 逗號是可選的? – JosephGarrone

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 
+0

你的答案的工作太偉大! –

相關問題