I am trying to replace any instances of uppercase letters that repeat themselves twice in a string with a single instance of that letter in a lower case. I am using the following regular expression and it is able to match the repeated upper case letters, but I am unsure as how to make the letter that is being replaced lower case.
JavaScript
x
5
1
import re
2
s = 'start TT end'
3
re.sub(r'([A-Z]){2}', r"1", s)
4
>>> 'start T end'
5
How can I make the “1” lower case? Should I not be using a regular expression to do this?
Advertisement
Answer
Pass a function as the repl
argument. The MatchObject
is passed to this function and .group(1)
gives the first parenthesized subgroup:
JavaScript
1
5
1
import re
2
s = 'start TT end'
3
callback = lambda pat: pat.group(1).lower()
4
re.sub(r'([A-Z]){2}', callback, s)
5
EDIT
And yes, you should use ([A-Z])1
instead of ([A-Z]){2}
in order to not match e.g. AZ
. (See @bobince’s answer.)
JavaScript
1
4
1
import re
2
s = 'start TT end'
3
re.sub(r'([A-Z])1', lambda pat: pat.group(1).lower(), s) # Inline
4
Gives:
JavaScript
1
2
1
'start t end'
2