python正则表达式重复模式
我正在寻找一个正则表达式来匹配:
[文件编号] m
为了仅在 n=m 时摆脱 [文档 n]
其中 n 是任意数字
所以 [document 34] 34 将匹配但 [document 34] 45 不会,因为数字不同
到目前为止,我有这个:
import re
text = "[document 23] 23 and [document 34] 48 are white"
text = re.sub(r"([document d+] )(d+)",r"2. ",text)
但这并不能保证数字相等。
任何的想法?
回答
您可以使用
[documents+(d+)]s+1(?!d)
请参阅正则表达式演示。替换为1。详情:
[document-[document字符串s+- 一个或多个空格(d+)- 第 1 组 (1):一位或多位数字]- 一个]字符s+- 一个或多个空格1- 对第 1 组的反向引用(?!d)- 如果当前位置右侧有一个数字,则匹配失败的负前瞻。
请参阅Python 演示:
import re
text = "[document 23] 23 and [document 34] 48 are white [document 24] 240 text"
print( re.sub(r'[documents+(d+)]s+1(?!d)', r'1', text) )
## => 23 and [document 34] 48 are white [document 24] 240 text