Python If-Then-Else正则表达式
我试图形成一个正则表达式,如果它在字符串中,它将捕获Python If-Then-Else正则表达式,python,regex,if-statement,Python,Regex,If Statement,我试图形成一个正则表达式,如果它在字符串中,它将捕获,否则将捕获 我尝试了一些类似的方法:(IF)(?(1)THEN | ELSE),这意味着如果(如果被找到)或者ELSE(如果没有找到),那么捕获将是 例如: (apple1\d)(?(1)|apple2\d) 案例1: 对于字符串:pear33 apple14 apple24 orange22 orange44 结果将是:apple14 案例2: 与字符串相反:pear33 apple24 orange22 orange44 结果将是:ap
,否则将捕获
我尝试了一些类似的方法:(IF)(?(1)THEN | ELSE)
,这意味着如果(如果被找到)或者ELSE
(如果没有找到),那么捕获将是
例如:
(apple1\d)(?(1)|apple2\d)
案例1:
对于字符串:pear33 apple14 apple24 orange22 orange44
结果将是:apple14
案例2:
与字符串相反:pear33 apple24 orange22 orange44
结果将是:apple24
(由于没有apple1
,它将捕获apple2\d
)
我的正则表达式在case1中运行良好,它返回apple14
,但是ELSE
不起作用。对于案例2,我希望它返回apple24
使用:
(?(?=apple1\d)apple1\d|apple2\d)
IF
部分应该是一个前瞻部分,因此在执行ELSE
分支时,它不包括在匹配要求中
如果不想重复中的If
表达式,则可以使用反向引用
(?(?=(apple1\d))\1|apple2\d)
编辑:使用search()代替findall()
第二个例子:
# with "if then else" in search string
string = 'pear33 if then else apple14'
match = re.search(r'if then|else', string)
print(match.group())
输出:
if then
else
['apple24']
搜索字符串中没有“如果”
string = 'pear33 then else apple14'
match = re.search(r'if then|else', string)
print(match.group())
输出:
if then
else
['apple24']
第一个例子
import re
string = 'pear33 apple24 orange22 orange44'
match = re.findall(r'(apple1\d|apple2\d)', string)
print(match)
输出:
if then
else
['apple24']
首先,我不确定为什么需要if-else语句(请参阅我答案的第2版),但我将尝试提供一些解决方案
因此,对我来说,@Barmer的解决方案()给了我错误:组名中的坏字符
,尽管我确信通过适当的调整,这可能是最佳解决方案
但是,在他回来之前,您可以尝试这些方法(尽管search.group()和search.groups()在处理捕获组/缺少捕获组方面确实让我有点恼火)
版本1:基于上述建议的解决方案的超特定版本。我认为我的解决方案不可取。
>>> import re
>>> string1 = 'pear33 apple14 apple24 orange22 orange44'
>>> string2 = 'pear33 apple24 apple14 orange22 orange44'
>>> re.findall('(?<!apple[12]\d)[\s]+(apple1\d|apple2\d)', string1)
['apple14']
>>> re.findall('(?<!apple[12]\d)[\s]+(apple1\d|apple2\d)', string2)
['apple24']
>>> re.search('(?<!apple[12]\d)[\s]+(apple1\d|apple2\d)', string1).group()
' apple14'
>>> re.search('(?<!apple[12]\d)[\s]+(apple1\d|apple2\d)', string2).group()
' apple24'
>>重新导入
>>>string1='pear33 apple14 apple24 orange22 orange44'
>>>string2='pear33 apple24 apple14 orange22 orange44'
>>>关于findall('(?)
>>string1='pear33 apple14 apple24 orange24'
>>>string2='pear33 apple24 apple14 orange22 orange44'
>>>关于findall('[\S\S]*?(苹果[\d]+)[\S\S]*',string1)
['apple14']
>>>关于findall('[\S\S]*?(苹果[\d]+)[\S\S]*',string2)
['apple24']
>>>关于findall(“(?您对pear33 apple24 apple14 orange22 orange44
(更改了14
和24
)的预期输出是什么?(如果)
是必须的。在它之后添加?
。但是,似乎您需要一个不同的正则表达式来解决真正的问题。使用2个正则表达式,只有在第一个正则表达式失败时才运行第二个正则表达式。if/ELSE只是向正则表达式添加模式。如果捕获不匹配任何内容,则整个正则表达式将不匹配。您应该使用前瞻作为if。@a\u guest expected值是apple14每当我尝试此操作时,我得到错误:组名中的坏字符
您能解释一下如何在Python中使用此正则表达式以获得所需的结果吗?尽管它没有完全解决问题,但它是一个很好的指导,我最终使用了apple1\d(?=.+apple2)| apple2\d可能有更好的方法来实现它:-)根据OP的评论,两个例子都应该返回apple14
。你得到的错误很可能是因为它应该是正则表达式中的(?:…)
,也就是说,缺少:
@a_guest确实是这样,但有趣的是,他在那篇文章中得到了+1和正确的答案。我不知道怎么做,所以我想知道它是如何工作的。