YoongKang Lim
YoongKang Lim

Reputation: 566

Regular expression match a sentence with specified word in a specified distance

How to match a sentence with Bacon and meat with distance of 2 or less than 2 words?

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

Bacon is pork meat    ----Match

I have tried:

^(\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

Upvotes: 0

Views: 258

Answers (2)

JosephGarrone
JosephGarrone

Reputation: 4161

Try the following regex:

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

You can see this live here.

Out of these:

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

It finds these:

Bacon is meat
Bacon is pork meat
Bacon meat

EDIT:

This can be shortened to (Live here):

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

Where the {0,2} means between 0 and 2 times. Changing to {0,3} would mean Bacon is not a meat would also be matched.

EDIT 2:

To match the , as well (Optional comma), (See it live here):

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

Out of these:

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

These are matched:

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

Upvotes: 2

froglegs
froglegs

Reputation: 143

This should work.

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

Upvotes: 1

Related Questions