Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.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,我的问题是,当按位运算符|左侧的第一项出现在句子中时,这个带有布尔运算符的简单正则表达式语句只会给出我想要的结果。有人能告诉我为什么它对替代方案不起作用吗 import re b = 'this is a good day to die hard' jeff = re.search('good night (.+)hard|good day (.+)hard', b) print jeff.group(1) 第二。。。创建需要使用.group2访问的第二个捕获组 您可以编写一个正

我的问题是,当按位运算符|左侧的第一项出现在句子中时,这个带有布尔运算符的简单正则表达式语句只会给出我想要的结果。有人能告诉我为什么它对替代方案不起作用吗

 import re

 b = 'this is a good day to die hard'

 jeff = re.search('good night (.+)hard|good day (.+)hard', b)

 print jeff.group(1)
第二。。。创建需要使用.group2访问的第二个捕获组

您可以编写一个正则表达式来捕获白天或黑夜,第二组将获取所有到最后一组的数据

报告的产出:


您有两组捕获括号-因此您有两个编号的捕获组。如果第二个分支匹配,group1将设置为None,group2将包含第二个组匹配的分支

有几种方法可以解决这个问题。例如,一种方法是编写,这样就只有一个组

jeff = re.search('good (?:day|night) (.+)hard', b)
因为第二个。。。创建第二个组。正则表达式中的|的专有名称为alternation。它不是真正的布尔值。
day
to die hard
jeff = re.search('good (?:day|night) (.+)hard', b)