首页 > 解决方案 > python 正则表达式重复模式

问题描述

我正在寻找一个正则表达式来匹配:

[文档 n] 米

为了仅在 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)

但这并不能保证数字是相等的。

任何的想法?

标签: pythonregex

解决方案


您可以使用

\[document\s+(\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'\[document\s+(\d+)]\s+\1(?!\d)', r'\1', text) )
## => 23 and [document 34] 48 are white [document 24] 240 text

推荐阅读