簡體   English   中英

正則表達式與我認為的不匹配

[英]Regular expression not matching what I think it should

在python中,我正在編譯一個正則表達式模式,如下所示:

rule_remark_pattern = re.compile('access-list shc-[(in)(out)] [(remark)(extended)].*')

我希望它與以下任何行匹配:

access-list shc-in remark C883101 Permit http from UPHC outside to Printers inside
access-list shc-in extended permit tcp object-group UPHC-Group-Outside object-group PRINTER-Group-Inside object-group http-https 
access-list shc-out remark C890264 - Permit (UDP 123) from UPHC-Group-Inside to metronome.usc.edu
access-list shc-out extended permit udp object-group UPHC-Group-Inside host 68.181.195.12 eq ntp 

不幸的是,它不匹配任何一個。 但是,如果我將正則表達式寫為:

rule_remark_pattern = re.compile('access-list shc-in [(remark)(extended)].*')

它與前兩個匹配就好了。

同樣,如果我寫:

rule_remark_pattern = re.compile('access-list shc-out [(remark)(extended)].*')

它匹配最后2個。

有人知道這是怎么回事嗎?

我的regex-fu不是基於Python的,但是假設它類似於標准,我認為您誤解了'['和']'的用法。 它們代表一個角色類 ,看來您需要交替

嘗試用“((word1 | word2)]”替換“ [(word1)(word2)]”結構。

編輯:剛剛檢查了Python文檔(在這里: http : //docs.python.org/library/re.html ),但我沒有看到Python regexen與我習慣的任何相關區別(即沒有應有的區別)影響此答案的准確性。)

這主要是因為您完全誤解了“定義替代項”在正則表達式中的工作方式:

access-list shc-(in|out) (remark|extended).*

您的嘗試將創建角色類。 字符類中的每個字符都獨立存在,並且類本身實際上僅與允許列表中的單個字符匹配。 因此,您可以嘗試:

[(in)(out)]

真的和

[intou(())]

實際上與[intou()]相同,因為字符類中的重復字符將被忽略。

暫無
暫無

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

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