簡體   English   中英

Python不匹配regexp

[英]Python not matching regexp

>>> pattern = re.compile(r'(.*)\\\\(.*)\\\\(.*)')
>>> m = re.match(pattern, 'string1\string2\string3')
>>> m
>>> 
>>> m.groups
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'

我正在嘗試在上面的正則表達式中使用以下格式匹配字符串: string1\\string2\\string3

以上是Python的輸出。 為什么它沒有返回適當的正則表達式對象? 我的模式有什么問題嗎?

問題是在你的模式中,你使用\\\\\\\\ ,它代表兩個原始反斜杠,而在要匹配的文本中,你使用\\s ,實際上根本沒有反斜杠(它是一個\\s字符)。

首先,您可能希望將文本設置為原始字符串,否則Python會將其作為\\s字符讀取。

re.match(pattern, r'string1\string2\string3')

其次,在模式中只需要兩個連續斜杠,以表示一個反斜杠:

pattern = re.compile(r'(.*)\\(.*)\\(.*)')

最后,你想做m.groups() (而不是m.groups ,而不是m.groups 因此,您的代碼將如下所示:

pattern = re.compile(r'(.*)\\(.*)\\(.*)')
m = re.match(pattern, r'string1\string2\string3')
m.groups()
# ('string1', 'string2', 'string3')

問題是你試圖逃避原始字符串中的反斜杠。 Python文檔中

當存在'r'或'R'前綴時,字符串中包含反斜杠后面的字符不會發生更改,並且所有反斜杠都保留在字符串中。

這意味着所有8個反斜杠都保留在正則表達式中,並且每對反射匹配測試字符串中的單個反斜杠。 當您可視化時 ,問題立即顯現(將滑塊拖動到測試字符串上方)。 它可以通過替換你的正則表達式來修復

r'(.*)\\(.*)\\(.*)'

暫無
暫無

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

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