re.sub('a(b)','d','abc')
yield dc
,不是 adc
.
为什么re.sub
替换整个捕获组,而不仅仅是捕获组'(b)'?
最佳答案
因为它应该替换整个模式的出现:
Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl.
如果它只替换某些子组,那么包含多个组的复杂正则表达式将不起作用。有几种可能的解决方案:
re.sub('ab', 'ad', 'abc')
- 我最喜欢的,因为它非常易读和明确。 re.sub('(a)b', r'\1d', 'abc')
repl
参数并使其处理 Match
对象并返回所需的结果。 re.sub('(?<=a)b', r'd', 'abxb')
yield adxb
. ?<=
在组的开头说“这是一个前瞻”。 关于python - 为什么 re.sub 替换整个模式,而不仅仅是其中的一个捕获组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42104540/