[英]What does regex return to python if it can't find a match
What does regex return to Python if it can't find a match in the string? 如果在字符串中找不到匹配项,则regex返回Python吗?
I'm trying to write an if function in python. 我正在尝试在python中编写if函数。 I have a list which contains 2 different ends of strings, and I'm trying to test the first regex and if it can't find anything, use else to run the other regex search. 我有一个包含2个不同字符串结尾的列表,我正在尝试测试第一个正则表达式,如果找不到任何东西,请使用else运行其他正则表达式搜索。
Is there another way I could approach this problem? 有没有其他方法可以解决这个问题?
The strings in the list end like: 列表中的字符串如下所示:
1. ...at Company A; Price $84
2. ...at Company B
I'm just looking to pull out Company A and Company B 我只是想退出公司A和公司B
I've already tried == None, [], '', False
in the if function. 我已经尝试过if函数中的== None, [], '', False
。
Here is my code for the Regex patterns. 这是我的Regex模式代码。 Both patterns work as I tested them separately for the entire list: 当我针对整个列表分别测试它们时,这两种模式都起作用:
analystcompanypattern = re.compile('(?<=at )(.*)(?=;)')
analystcompanypattern_noPrice = re.compile('(?<=at )(\w+)$')
if str(analystcompanypattern_noPrice.findall(test)) == None:
analyst_company = str(analystcompanypattern.findall(test))
else:
analyst_company = str(analystcompanypattern_noPrice.findall(test))
I'm trying to figure out what to put where None is if regex can't find a match, getting analyst companies for values ending with the price and getting [] for ending like 2., for strings with 'company'. 我试图弄清楚如果正则表达式找不到匹配项,则将无处放在什么位置,让分析公司获取以价格结尾的值,让[]结尾像2的值,并获取“ company”的字符串。
It returns a list with the matched sequence(s). 它返回具有匹配序列的列表。 If there is no match, the list will be empty. 如果没有匹配项,则列表将为空。
To test if the list is empty or not: 要测试列表是否为空:
if len(analystcompanypattern_noPrice.findall(test)) == 0:
you can try (no need for conditions) 您可以尝试(无需条件)
re.search('at ([^;]*)',str)
>>> str='...at Company B'
>>> m = re.search('at ([^;]*)',str)
>>> m.group(1)
>>> 'Company B'
>>>
>>>
>>> str='...at Company A;price 2'
>>> m = re.search('at ([^;]*)',str)
>>> m.group(1)
>>> 'Company A'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.