Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for capitalized backreference

Tags:

regex

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?

like image 348
user2565010 Avatar asked Oct 26 '25 21:10

user2565010


1 Answers

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