Search code examples
pythonregexarcpy

python regex prevent nonetype error


I have code below that searches for a pattern and assigns the pattern to a variable num if the pattern exists.

for row1 in cursor1:
    try:
        m = re.search(r"^[0-9]+(?=\s)", row1[0])
        num = m.group()
    except Exception as e:
        pass

I then use the num variable in the code below:

z1=(item for item in numlist if item[6]==num and harversine.myhaversine(custx,custy,item[2],item[3])<150)

I would like to eliminate the num variable and compare text that matches the regex directly to item[6] as in if item[6]==re.search(r"^[0-9]+(?=\s)",row1[0]).group() But of course this will give me an error for the rows that don't have the pattern. How do I achieve what I am trying to do without getting the nonetype has no attribute group() error? PS: The overall code not shown here loops through rows, creates tuples and assigns necessary values based on fulfillment of the if statement. I want to change the regex matching part shown in the code for better performance because not all rows use the num variable. I want the regex to be run only for the rows that use this variable.


Solution

  • As Karoly Horvath has pointed out, you can make use of the fact that text that doesn't match returns None object

    In [2]: m = re.search(r"^[0-9]+(?=\s)", row1[0])
    Out [2]: None
    

    You can use this in if condition

    z1=(item for item in numlist if (re.search(r"^[0-9]+(?=\s)",row1[0]) and item[6]==re.search(r"^[0-9]+(?=\s)",row1[0]).group()) and harversine.myhaversine(custx,custy,item[2],item[3])<150)
    

    return value of re.search(r"^[0-9]+(?=\s)",row1[0]) ie, None will evaluate to false making value of whole condition false.