Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式与我认为应该的不匹配_Python_Regex - Fatal编程技术网

Python 正则表达式与我认为应该的不匹配

Python 正则表达式与我认为应该的不匹配,python,regex,Python,Regex,在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 ob

在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个匹配


有人知道这里发生了什么吗?

我的正则表达式fu不是基于Python的,但假设它是标准的,我想你误解了“[”和“]”的用法。它们代表一个字符类,似乎您需要一个交替

尝试将“[(word1)(word2)]”结构替换为“(word1 | word2)”


编辑:刚刚检查了Python文档(这里:),我没有看到Python正则表达式和我习惯的正则表达式之间有任何相关的区别(即没有任何东西会影响这个答案的准确性)。

我的正则表达式fu不是基于Python的,但假设它是标准的,我想你误解了“[”和“]”的用法。它们代表一个字符类,似乎您需要一个交替

尝试将“[(word1)(word2)]”结构替换为“(word1 | word2)”


编辑:刚刚检查了Python文档(此处:),我看不到Python正则表达式和我习惯的正则表达式之间有任何相关差异(即没有任何东西会影响此答案的准确性)。

这主要是因为您完全不理解正则表达式中“定义替代项”的工作原理:

access-list shc-(in|out) (remark|extended).* 访问列表shc-(输入|输出)(备注|扩展)*
您的尝试将创建角色类。字符类中的每个字符都独立存在,而类本身实际上只匹配允许列表中的单个字符。因此,您可以尝试:

[(in)(out)] [(输入)(输出)] 真的是一样的吗

[intou(())] [intou(())]
这实际上与
[intou()]
相同,因为字符类中的重复字符被忽略。

这主要是因为您完全不理解正则表达式中“定义替代项”的工作原理:

access-list shc-(in|out) (remark|extended).* 访问列表shc-(输入|输出)(备注|扩展)*
您的尝试将创建角色类。字符类中的每个字符都独立存在,而类本身实际上只匹配允许列表中的单个字符。因此,您可以尝试:

[(in)(out)] [(输入)(输出)] 真的是一样的吗

[intou(())] [intou(())] 这实际上与
[intou()]
相同,因为字符类中的重复字符被忽略