簡體   English   中英

Python3 正則表達式不匹配

[英]Python3 regex not match

我正在嘗試使用 re.findall 匹配字符串,但它不匹配任何內容:

>>> str = ''' description TESTE ONE Gi0/0/0\n ip vrf forwarding test\n ip address       xxx.xxx.xxx.xxx\n ip flow monitor fnf input\n ip flow monitor fnf output\n negotiation    auto\n cdp enable\n'''
>>> print(str)
     description TESTE ONE Gi0/0/0
     ip vrf forwarding test
     ip address xxx.xxx.xxx.xxx
     ip flow monitor fnf input
     ip flow monitor fnf output
     negotiation auto
     cdp enable
     >>> desc = re.findall(r'^ description (.*)$', str)
     >>> desc
         []"

在 regex101.com 中,相同的正則表達式正常工作。

差異是由點 ( . ) 字符的行為引起的。 Python 的正則表達式語法中, . 默認情況下不匹配換行符,因此字符串中的換行符會導致(.*)組不匹配。

行為或. 可以通過將re.DOTALL標志傳遞給方法來更改:

re.findall(r'^ description (.*)$', str, re.DOTALL)

ApproachingDarknessFish 提供的答案是正確的,如果您嘗試匹配所提供的“描述”之后的整個輸入字符串。 但是,您正在執行findall ,這強烈表明您正在尋找多次出現的^ description (.*)$ ,因此您的意思是錨^$代表的開始和結束,而不是開始和結束的整個字符串。 如果是這種情況,那么您不想使用re.DOTALL標志,而是使用re.M標志:

import re

str = ''' description TESTE ONE Gi0/0/0
 ip vrf forwarding test
 ip address       xxx.xxx.xxx.xxx
 ip flow monitor fnf input 
 ip flow monitor fnf output
 negotiation    auto
 cdp enable
 description another one thrown in for good measure!
'''
print(re.findall(r'^ description (.*)$', str, re.M))

印刷:

['TESTE ONE Gi0/0/0', 'another one thrown in for good measure!']

暫無
暫無

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

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