python - 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)
但这并不能保证数字是相等的。
任何的想法?
解决方案
您可以使用
\[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
推荐阅读
- python - 我们如何使用 Entry 来设置 Timer 上的时间?(Python,tkinter)
- javascript - 如何在谷歌应用脚本中解析带有嵌套数组的 JSON 对象
- bash - ping google.com 以查看 vpn-server 是否已启动,如果已关闭,请重新连接到另一个
- sql - 将字符串格式的日期转换为日期数据类型 sql
- r - 从 R 中的 Google Drive 下载 xlsx 文件
- node.js - node.js aws sns 控制台测试和 npm run 发布消息之间的区别
- html - 隐藏在容器上的 CSS 边框半径和溢出使内容渗透 1 px
- jupyter-notebook - 当我创建一个新的 jupyter 笔记本(python 3.9)时,一半的 jupyter 笔记本设置是用俄语(西里尔文)写的,另一半是英文的
- powershell - 安装 VS Code 后如何修复 powershell
- flutter - Flutter教程为“中心”内的两个“孩子”获取“已指定命名参数“孩子”的参数”