Home > OS >  Is there a regulair expression for "match the following in any order" or "match any p
Is there a regulair expression for "match the following in any order" or "match any p

Time:09-26

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

CodePudding user response:

You can try the following:

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

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

CodePudding user response:

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!)

  • Related