使用正则表达式替换单词时,是否有一种优雅的方式来表示我希望替换符合替换单词的第一个字母的大写/小写?
foo -> bar
Foo -> Bar
foO -> bar
不区分大小写的替换示例,但它不能正确地将Foo
替换为Bar
(而是bar
替换)。
re.sub(r'\bfoo\b', 'bar', 'this is Foo', flags=re.I)
# 'this is bar'
答案 0 :(得分:4)
没有任何开箱即用的东西。您需要使用替换功能。
import re
def cased_replacer(s):
def replacer(m):
if m.group(0)[0].isupper():
return s.capitalize()
else:
return s
return replacer
re.sub(r'\bfoo\b', cased_replacer('bar'), 'this is foo', flags=re.I)
# => 'this is bar'
re.sub(r'\bfoo\b', cased_replacer('bar'), 'this is Foo', flags=re.I)
# => 'this is Bar'
答案 1 :(得分:2)
简答:不。
答案很长:
您可以使用finditer
访问所有匹配项,然后手动执行大小写匹配。
tests = (
"11foo11",
"22Foo22",
"33foO33",
"44FOO44",
)
import re
foobar = "(?i)(foo)"
for teststr in tests:
replstr = "bar"
newchars = list(teststr)
for m in re.finditer(foobar, teststr):
mtext = m.group(1)
replchars = list(replstr)
for i, ch in enumerate(mtext):
if ch.isupper():
replchars[i] = replchars[i].upper()
newchars[m.start():m.end()] = replchars
print("Old: ", teststr, " New: ", ''.join(newchars))