-2

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.

7
  • put the assignment of item[6] inside of a try block and the comprehension inside of your else block for the aforementioned try Commented Nov 20, 2015 at 21:21
  • 1
    "NoneType has no attribute group" - I'm sure you know how to check for None... Commented Nov 20, 2015 at 21:22
  • @R Nar unfortunately I can't go that route because item[6] is being generated inside the comprehension and I am using generators so I need it to be where it's at. Commented Nov 20, 2015 at 22:01
  • @Karoly Horvath I am sorry but I don't understand what you mean. Commented Nov 20, 2015 at 22:02
  • Do you want to assign value of num to item[6] or compare it in the if condition? Commented Nov 24, 2015 at 13:44

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Pleasure to know it worked for you. I liked the bit where you corrected the typo in my edit

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.