Multiple Matches Using Regular Expressions

Regular Expressions No Comments »

Let’s say you have a string and you want to test if it contains the substrings foo, bar, and baz in any order. To do this using regular expressions, you have the following options:

  1. Test for /foo/, /bar/, and /baz/ independently and serially in your code. This is the easiest solution, but it is kind of cheating.
  2. Write a single regular expression that has all possible orderings of the substrings, i.e. /foo.*bar.*baz|foo.*baz.*bar|bar.*foo.*baz|.../. This doesn’t scale, as you have to write n! combinations.
  3. Use lookahead assertions, i.e. /(?=.*foo)(?=.*bar)(?=.*baz)/. This may not be supported by all regular expression engines, and you may run into issues of overlap.
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in