Search code examples
pythonregexregex-negation

Inverse Regex matching street address


I'm trying to create a regex expression. I looked at this stackoverflow post and some others but I haven't been able to solve my problem.

I'm trying to match part of a street address. I want to capture everything after the directional.

Here are some examples

5XX N Clark St

91XX S Dr Martin Luther King Jr Dr

I was able to capture everything left of the directional with this pattern.

\d+[X]+\s\w

It returns 5XX N and 91XX S

I was wondering how I can take the inverse of the regex expression. I want to return Clark St and Dr Martin Luther King Jr Dr.

I tried doing

(?!\d+[X]+\s\w)

But it returns no matches.


Solution

  • Use the following pattern :

    import re
    s1='5XX N Clark St'
    s2='91XX S Dr Martin Luther King Jr Dr'
    pattern="(?<=N|S|E|W).*"
    k1=re.search(pattern,s1)
    k2=re.search(pattern,s2)
    print(k1[0])
    print(k2[0])
    
    

    Output:

    Clark St
    Dr Martin Luther King Jr Dr