python - Python查找所有出现的连字符并替换位置
问题描述
我必须用最后一个标记(即或在本例中)用连字符(如c-c-c-c-come
oroh-oh-oh-oh
等)替换所有出现的模式,其中come
oh
- 连字符之间的字符数是任意的,可以是一个或多个字符
- 要匹配的标记是连字符中的最后一个标记,因此
come
在c-c-come
. 输入字符串可能出现一次或多次,如以下句子:
c-c-c-c-come to home today c-c-c-c-come to me
oh-oh-oh-oh it's a bad life oh-oh-oh-oh
需要通过以下方式找到匹配token的开始和结束位置
finditer
r = re.compile(pattern, flags=re.I | re.X | re.UNICODE) for m in r.finditer(text): word=m.group() characterOffsetBegin=m.start() characterOffsetEnd=m.end() # now replace and store indexes
[更新]
假设这些连字符不属于固定字典,我将添加此约束:
- 连字符之间的字符数必须从最小值到最大值,这样
{1,3}
捕获组必须匹配c-come
, 或c-c-come
,但不能匹配带连字符的真实单词 likefine-tuning
或 likeinter-face
等。
解决方案
您可以只使用re.sub()
来替换所有,而不必遍历匹配的索引:
import re
s = 'c-c-c-c-come to home today c-c-c-c-come to me'
print(re.sub(r'(\w+(?:-))+(\w+)', '\\2', s))
# come to home today come to me
推荐阅读
- vhdl - 如何将单个 STD_LOGIC 位作为参数而不是 STD_LOGIC_VECTOR
- caching - 如何在 Gitlab CI 中使用参考仓库
- x509certificate - Windowscryptographicexception - 指定的网络密码不正确
- java - OpenApi 生成器:使用 Long 作为数字默认值?
- node.js - AWS Lambda 函数似乎挂起
- json - Firebase 'GET' API 返回大量 uneccesarry 数据
- mysql - 如何创建具有 if 条件的 SQL 触发器?
- javascript - 地理位置行为
- css - 导航不应该是全宽,而是内容的宽度
- verilog - 我的输出总是驱动 10110 模式检测器的 Z 值