[英]Python- Replace all occurrences of letter at specific position on a string
[英]Python find all occurrences of hyphenated word and replace at position
我有一个连字符替换的模式所有出现像cccc-come
或oh-oh-oh-oh
,等等与最后一个记号即come
或oh
在这个例子中,在
come
在cc-come
。 输入字符串可能有一个或多个出现,如以下句子:
cccc-come to home today cccc-come to me
oh-oh-oh-oh it's a bad life oh-oh-oh-oh
需要通过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
[UPDATE]
假设那些带连字符的单词不属于固定词典,那么我要向其添加以下约束:
{1,3}
以便捕获组必须匹配c-come
或cc-come
,但不能与诸如fine-tuning
或inter-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
这是一个可能的表达式:
import re
text = ("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")
pattern = r"(?<=-)\w+(?=[^-\w])"
r = re.compile(pattern, flags=re.I | re.X | re.UNICODE)
for m in r.finditer(text):
word = m.group()
characterOffsetBegin = m.start()
print(word, characterOffsetBegin)
输出:
come 8
come 35
oh 56
使用捕获组和反向引用的选项可能是:
(?<!\S)(\w{2,3})(?:-\1)*-(\w+)(?!\S)
这将匹配:
(?<!\\S)
负向后看,断言左侧的内容不是非空格字符 (\\w{2,3})
在组1中捕获一个单词char的两倍或三倍 (?:-\\1)*
重复0+次匹配连字符,然后反向引用组1中匹配的内容 -(\\w+)
匹配-
随后匹配组2中的1个以上的字符字符 (?!\\S)
负向超前,断言右侧的内容不是非空格字符 在替换中,使用第二个捕获组\\\\2
或r'\\2
例如
import re
text = "c-c-c-c-come oh-oh-oh-oh it's a bad life oh-oh-oh-oh"
pattern = r"(?<!\S)(\w{1,3})(?:-\1)*-(\w+)(?!\S)"
text = re.sub(pattern, r'\2', text)
print(text)
结果
come oh it's a bad life oh
无需正则表达式即可完成。 码:
s = "c-c-c-c-come to home today c-c-c-c-come to me"
s = " ".join(w if "-" not in w else w[w.rindex('-') + 1:] for w in s.split(" "))
输出:
come to home today come to me
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.