Python Forum

Full Version: Conditional RegEx
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I'd like the RegExs below to output 'NULL' when they don't find a match but I haven't figured out how to do this. I'd like to do this so that when I can display flight1 and flight2 in a DataFrame. Otherwise, I get the error 'All arrays must be the same lenght'. Can anyone help?

for i in range(0,5):
    text = doc.getPage(i).extractText()
flight1_re = re.compile(r'E *\d{3}\s') 
    for match in flight1_re.findall(text):
        flight1 = match(text)
    else:
        flight = 'NULL'
        print(flight)

flight2_re = re.compile(r'E *\d{3}\s') 
    for match in flight2_re.findall(text):
        flight2 = match(text)
    else:
        flight2 = 'NULL'
        print(flight2)
Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-d985b6080e6e> in <module>
21 flight_re = re.compile(r'E *\d{6}\s')
22 for match in flight_re.findall(text):
---> 23 flight = match(text)
24 else:
25 flight = 'NULL'

TypeError: 'str' object is not callable
flight1_re = re.compile(r'E *\d{3}\s') 
    for match in flight1_re.findall(text):
        flight1 = match(text)
    else:
        flight = 'NULL'
        print(flight)
In the loop on line2, match is set in turn to the matching string from the source, so it is a str.
On line 3, you are asking for the value of match(text). As match is a str, it can't be called with an argument. I think you may just be intending to have it similar to

flight1 = match
(Feb-18-2021, 05:49 PM)bowlofred Wrote: [ -> ]
flight1_re = re.compile(r'E *\d{3}\s') 
    for match in flight1_re.findall(text):
        flight1 = match(text)
    else:
        flight = 'NULL'
        print(flight)
In the loop on line2, match is set in turn to the matching string from the source, so it is a str.
On line 3, you are asking for the value of match(text). As match is a str, it can't be called with an argument. I think you may just be intending to have it similar to

flight1 = match


Thanks for the insight, bowlofred. I have revised the code and now it works. Much appreciated!