2

Gives a set of regular expressions r_1, r_2, r_3, ..., r_n is there a regular expression which could be interpreted to say something similar to:

  • match any permutation of r_1, r_2, r_3, ..., r_n
  • match all of the following in any order: r_1, r_2, r_3, ..., r_n

The regular expression a|b|c...

  • matches the letter a
  • matches the letter b
  • does not match the entire string cab. The regex will only align with exactly one letter from cab

For a given example, I could write down each and every permutation. The following is rather verbose:

ABC|BAC|CAB|ACB|BCA|CBA

justsomeguy
  • 513
  • 4
  • 11
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
  • What about duplicates? Should they match? Like `aabc`. – Poul Bak Sep 24 '22 at 01:15
  • Does this answer your question? [Regex: I want this AND that AND that... in any order](https://stackoverflow.com/questions/3533408/regex-i-want-this-and-that-and-that-in-any-order) – Karl Knechtel Apr 28 '23 at 04:12

2 Answers2

3

Use a combination of look aheads and length:

^(?=.*a)(?=.*b)(?=.*c).{3}$

This approach scales linearly, ie the regex has length O(n), when adding more terms, even though the permutations it matches grow factorially, ie O(n!)

Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

You can try the following:

^(?=[A-C]{3}$)(?!.*(.).*\1).*$

Here's a link to play around with it on regex101.com

justsomeguy
  • 513
  • 4
  • 11