![](/img/trans.png)
[英]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.