简体   繁体   中英

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?

I'm trying to write an if function in python. 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.

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

I've already tried == None, [], '', False in the if function.

Here is my code for the Regex patterns. 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'.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM