[英]Updating a string using regular expressions in Python
我很確定我的問題很簡單,但是找不到答案。 假設我們有一個輸入字符串,例如:
input = "This is an example"
現在,我想簡單地用一個包含原始字符串的字符串替換輸入中的每個單詞(通常來說,每個子字符串都使用正則表達式 ,這里的“ word”只是一個示例)。 例如,我想在輸入中每個單詞的左側和右側添加一個@
。 並且,輸出將是:
output = "@This@ @is@ @an@ @example@"
解決辦法是什么? 我知道如何使用re.sub
或replace
,但是我不知道如何使用它們可以更新原始匹配的字符串而不用其他東西完全替換它們。
您可以為此使用捕獲組。
import re
input = "This is an example"
output = re.sub("(\w+)", "@\\1@", input)
捕獲組是您以后可以引用的內容,例如在替換字符串中。 在這種情況下,我要匹配一個單詞,將其放入捕獲組,然后將其替換為相同的單詞,但是將@
添加為前綴和后綴。
您可以在docs中了解有關python中的正則表達式的更多信息。
這是使用re.sub
進行環視的選項:
input = "This is an example"
output = re.sub(r'(?<!\w)(?=\w)|(?<=\w)(?!\w)', '@', input)
print(output)
@This@ @is@ @an@ @example@
這是沒有重新圖書館
a = "This is an example"
l=[]
for i in a.split(" "):
l.append('@'+i+'@')
print(" ".join(l))
您只能使用\\b
匹配單詞邊界:
import re
input = "This is an example"
output = re.sub(r'\b', '@', input)
print(output)
@This@ @is@ @an@ @example@
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.