Search code examples
regexrandomregex-group

Regex match group with elements in random order


For simplicity sake, let's say I have the following literal string:

abc[4;?;z;*]def

where 4, ?, z and * can appear in random order, are separated by a ; , and are characters (or strings) that i know beforehand.

I have this regex that matches the string using 'or' groups:

abc\[(?:z|\*|4|\?|\;)+\]def

The problem is that is still matching if one of the elements is missing in the string, and I want to check if all are present:

abc[?;z;*]def

Capturing groups are irrelevant for me. I just want to confirm the whole string.


Solution

  • You can use

    abc\[(?=[^][]*z)(?=[^][]*4)(?=[^][]*\?)(?=[^][]*;)(?=[^][]*\*)[z*4?;]+]def
    

    See the regex demo. Details:

    • abc\[ - a literal abc[ string
    • (?=[^][]*z) - after zero or more chars other than [ and ], there must be a z
    • (?=[^][]*4) - after zero or more chars other than [ and ], there must be a 4
    • (?=[^][]*\?) - after zero or more chars other than [ and ], there must be a ?
    • (?=[^][]*;) - after zero or more chars other than [ and ], there must be a ;
    • (?=[^][]*\*) - after zero or more chars other than [ and ], there must be a *
    • [z*4?;]+ - one or more chars in the set, z, *, 4, ?, ;
    • ]def - a literal ]def string.