簡體   English   中英

re.sub“(-)”失敗

[英]re.sub “(-)” failed

我無法在Python中使用re.sub替換字符串“(-)”。

>>> instr = 'Hello, this is my instring'
>>> re.sub('my', 'your', instr)
'Hello, this is your instring'
>>> instr = 'Hello, this is my (-) instring'
>>> re.sub('my (-)', 'your', instr)
'Hello, this is my (-) instring'

有人可以給我提示我做錯了什么嗎?

謝謝!

re.sub(r'my \(-\)', 'your', instr)

您必須轉義括號,通常用於匹配組。 另外,在字符串前面添加r以保持其原始(由於反斜杠)。

或者根本不使用regexp(如果您的替換就這么簡單),並且您不必關心許多問題:

>>> instr = 'Hello, this is my (-) instring'
>>> instr.replace('my (-)', 'your')
'Hello, this is your instring'

就正則表達式引擎而言,您需要轉義'(-)'因為它是正則表達式模式匹配。 如果您不確定如何轉義,但是您的字符串沒有任何實際模式,但應逐字解釋,則應執行以下操作:

>>> re.sub(re.escape('my (-)'), 'your', instr)
'Hello, this is your instring'

或者,如果您的字符串是“普通”模式和復雜內容之間的混合,則可以執行以下操作:

>>> re.sub('[a-z]{2} %s' % re.escape('(-)'), 'your', instr)
'Hello, this is your instring'

調試這種事情的一種方法是使用re.DEBUG標志

>>> import re

>>> p = re.compile("my (-)", re.DEBUG)
literal 109 # chr(109) == "m"
literal 121 # chr(121) == "y"
literal 32 # chr(32) == " "
subpattern 1 # a group
  literal 45 # chr(45) == "-"
<_sre.SRE_Pattern object at 0x1004348a0>

因此,它與一個組中的“-”匹配,與文字(相比,在何處匹配:

>>> re.compile(r"my \(-\)", re.DEBUG)
literal 109
literal 121
literal 32
literal 40 # chr(40) == "(", not a group this time
literal 45
literal 41
<_sre.SRE_Pattern object at 0x10043ea48>

(我添加了#之后的內容,不是來自調試輸出)

暫無
暫無

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

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