在 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)].*')
它与前 2 个匹配得很好。
同样,如果我写:
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 和我习惯的有任何相关差异(即没有任何东西会影响这个答案的准确性。)
关于python - 正则表达式与我认为应该匹配的不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3197013/