Search code examples
regexpcre

Regex match if there is only one match from a number of choices in a string


Is there a pattern for finding if there is only one match from a number of options in a string?

Let's say we have the following list of potential matches:

`foo|bar|baz`

And we have the strings:

`Foo bar, Cambaz!` // shoud not match due to multiple findings
`My bar, good!` // shoud match for `bar`
`My friend, Cambaz!` // shoud match for baz

Case insensitive.


Solution

  • You may use this PCRE regex:

    ^(?>.*?(foo|bar|baz)){2}.*(*SKIP)(*F)|(?1)
    

    RegEx Demo

    • (*F) or (*FAIL) verb behaves like a failing negative assertion and is a synonym for (?!)
    • (*SKIP) defines a point beyond which the regex engine is not allowed to backtrack when the subpattern fails later
    • The idea of the (*SKIP)(*FAIL) trick is to consume characters that you want to avoid, and that must not be a part of the match result.
    • (?1): recurses the 1st subpattern