簡體   English   中英

使用正則表達式python在字符串中多次替換數字

[英]Multiple substitutions of numbers in string using regex python

當我使用re.sub改變其他兩個單詞的字符串中的兩個單詞時,我得到了輸出。 但是,當我嘗試數字輸出不正確

>>> import re
>>> a='this is the string i want to change'
>>> re.sub('(.*)is(.*)want(.*)','\\1%s\\2%s\\3' %('was','wanted'),a)
'this was the string i wanted to change'
>>> re.sub('(.*)is(.*)want(.*)','\\1%s\\2%s\\3' %('was','12345'),a)
'this was\x8a345 to change'
>>>

我不知道為什么會發生這種情況你可以提前告訴我如何使用這個謝謝

會發生什么事情,你傳遞的替換r'\\1was\\212345\\3' ,Python無法確定你是否需要反向引用號r'\\1was\\212345\\3' ,.... 它只選擇最大的一個,212345,這顯然不是表達式中的組索引。 因此,Python決定你的意思是bytestring文字b'\\212' ,這是一種編寫b'\\x8a'的奇怪方式。

要解決歧義,請使用長后向引用語法\\g<GROUP_NUMBER_HERE>

>>> re.sub('(.*)is(.*)want(.*)','\\g<1>%s\\g<2>%s\\g<3>' %('was','12345'),a)
'this was the string i 12345 to change'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM