ajt*_*ajt 27 python regex capitalization
我试图替换任何大写字母的实例,它们在一个字符串中重复两次,并在小写字母中包含该字母的单个实例.我使用以下正则表达式,它能够匹配重复的大写字母,但我不确定如何使被替换的字母小写.
import re
s = 'start TT end'
re.sub(r'([A-Z]){2}', r"\1", s)
>>> 'start T end'
Run Code Online (Sandbox Code Playgroud)
如何制作"\ 1"小写字母?我不应该使用正则表达式来执行此操作吗?
jen*_*ram 43
传递函数作为repl参数.将MatchObject被传递给这个函数,并.group(1)给出了第一个括号分组:
import re
s = 'start TT end'
callback = lambda pat: pat.group(1).lower()
re.sub(r'([A-Z]){2}', callback, s)
Run Code Online (Sandbox Code Playgroud)
编辑
是的,你应该使用([A-Z])\1而不是([A-Z]){2}为了不匹配,例如AZ.(见@ bobince的回答.)
import re
s = 'start TT end'
re.sub(r'([A-Z])\1', lambda pat: pat.group(1).lower(), s) # Inline
Run Code Online (Sandbox Code Playgroud)
得到:
'start t end'
Run Code Online (Sandbox Code Playgroud)
您无法在替换字符串中更改大小写.你需要一个替换功能:
>>> def replacement(match):
... return match.group(1).lower()
...
>>> re.sub(r'([A-Z])\1', replacement, 'start TT end')
'start t end'
Run Code Online (Sandbox Code Playgroud)