Struggling with a regex – Stack Overflow

You don’t specify what flavour of regex you are trying to use.

It is easier with more powerful regex features but can be done with just simple features.

With whitespace to increase legibility:

^

(
    ([^AX]|A([^B]|$)|AB([^C]|$)|X([^Y]|$)|XY([^Z]|$))*
    ABC
){2}

(
    ([^AX]|A([^B]|$)|AB([^C]|$)|X([^Y]|$)|XY([^Z]|$))*
    XYZ
){3}

([^AX]|A([^B]|$)|AB([^C]|$)|X([^Y]|$)|XY([^Z]|$))*

$

The long complicated lines translate to:

  • anything that isn’t the first character of one of the two strings ABC,XYZ
  • OR anything that is the first character not followed by the second
  • OR anything that is the first two characters not followed by the third
    (
        [^AX]          |
        A   ( [^B]|$ ) |
        A B ( [^C]|$ ) |
        X   ( [^Y]|$ ) |
        X Y ( [^Z]|$ )
    )*

If you have lookaheads, this can be more simply written using ((?!(ABC|XYZ)).)*:

^
(
    ((?!(ABC|XYZ)).)*
    ABC
){2}
(
    ((?!(ABC|XYZ)).)*
    XYZ
){3}
((?!(ABC|XYZ)).)*
$

and if you have (DEFINE) and recursive subpatterns:

^((?P>stuff)ABC){2}((?P>stuff)XYZ){3}(?P>stuff)$
(?(DEFINE)(?<stuff>((?!(ABC|XYZ)).)*))

Read more here: Source link