Search code examples
regexregex-negationregex-lookaroundsregex-groupregex-greedy

RegEx for matching everything except a repeating char at start and end


I have a string pattern and the examples are below.

AA4grgrsragrga4334grAA

AAA4323425AAA

AAAAAA%%%AAAAAA

Leading 'A's and trailing As always appear in pair.

I have tried:

A+.+A+

No idea how to pair up the leading As and trailing As in REGEX.


Solution

  • If you als want to match paired A's at the start and the end for strings like AA, or AAAAAA but also AAteAstAA you could use an alternation:

    ^(A+)(?:[^A].*[^A]|[^A])?\1$
    

    About the pattern

    • ^ Start of string
    • (A+) Capture in the first group matching 1+ A's
    • (?: Non capturing group
      • [^A].*[^A] Match not A, 0+ times any char except newline, then again not A
      • | Or
      • [^A] Match not A
    • )? Close non capturing group and make it optional
    • \1 Back reference to group 1
    • $ End of string

    Regex demo

    If AAA can also match you can use

    ^(A+)(?:[^A].*[^A]|.)?\1$
    

    Regex demo