Kenneth P.
Kenneth P.

Reputation: 1816

My PCRE Regex Pattern for detecting a String with Many Words is not Working

I would love to detect the following strings only:

pets ok
pets yes
pets allowed
pets accepted
pets is/are allowed
pets is/are accepted
pets will be considered
pets will considered
pets is/are considered
pet friendly

and the same thing with the reverse like:

ok pets
yes pets
...

(same as above, just with "pets"/"pet" from beginning at the end)

I can not figure this out.

Please, if you can help me improve my current pattern which is obviously not working:

/\\b(pet(?:s)?\\s[negotiable|ok|o\\.k|friendly|accept|allow|possible]+|[ok|yes|accept]+\\spet(?:s)?|pet(?:s)?\\s[will|will\\sbe]+\\s[consider|allow|accept|possible]+)\\b/i"

Upvotes: 0

Views: 110

Answers (2)

ohaal
ohaal

Reputation: 5268

Here is a super-strict regex which will only match the examples you listed (and didn't finish listing):

\b(?:(?:pets (?:ok|yes|(?:(?:is\/are )?(?:allowed|accepted))|(?:(?:will(?: be)?|is\/are) considered)))|(?:(?:ok|yes|(?:(?:is\/are )?(?:allowed|accepted))|(?:(?:will(?: be)?|is\/are) considered))) pets|pet friendly|friendly pet)\b​

See it on Rubular

I basically split it up into the variations of "allowed/accepted" and the variations of "considered". Then I just copied it for the opposite way.

The most human readable form would still be:

\b(?:pets ok|pets yes|pets allowed|pets accepted|pets is\/are allowed|pets is\/are accepted|pets will be considered|pets will considered|pets is\/are considered|pet friendly|ok pets|yes pets|allowed pets|is\/are allowed pets|accepted pets|is\/are accepted pets|will be considered pets|will considered pets|is\/are considered pets|friendly pet)\b

Also, in your regex, you seem to be using character classes ([ ]) for seperating words, when you should in fact be using non-capture groups ((?: ))

Upvotes: 0

Konstantin
Konstantin

Reputation: 493

Try

"/\\bpets?\\s[ok|is\\/are allowed]/i" 

and silimar

Upvotes: 2

Related Questions