Search code examples
regex

Regex for capitalized backreference


I'm trying to create the regex that highlights any group of two consecutive letters where the latter is the capitalized version of the former (which is lowercase).

For example, in the string

aSsdDsaAdfF

I want dD, aA and fF to match my given regex. To put it in another way, the string with highlights shouls be

aSsdDsaAdfF

I think I need to use backreferences, but I don't know how.

Could anybody please give me a way to solve this issue?


Solution

  • One way is this (?-i:([a-z])(?=[A-Z]))(?i:\1)
    which uses entirely localized case modifiers that don't affect anything
    else.

    Explanation

     (?-i:                         # Cluster group with 'case sensitive' scoped modifier
          ( [a-z] )                     # (1), Lower-case
          (?= [A-Z] )                   # Lookahead, Upper-case
     )                             # End cluster
     (?i:                          # Cluster group with 'case insensitive' scoped modifier
          \1                            # Backreference to group 1
                                        # ( previous assertion guarantees this
                                        #   can only be the Upper-Cased version of group 1) 
     )                             # End cluster