Jul 20
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:
- Test for
/foo/,/bar/, and/baz/independently and serially in your code. This is the easiest solution, but it is kind of cheating. - 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. - 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.
Recent Comments