Select to view content in your preferred language

Simple Regex refuses to work

437
3
Jump to solution
12-11-2023 10:36 AM
ccowin_odfw
Frequent Contributor

So I have addresses that have a zip in one field, and I want to extract the zip to a new field. Literally, the simplest regex that you can do.

 

This works fine in Python and returns 97321:

import re

address = '97321'
postal_code = re.search(r'.*(\d{5}(\-\d{4})?)$', address)
print(postal_code.group())

 

In Pro, in Calculate Field it acts like postal_code is None every single time, but I dont know because there is no way to properly debug this so I have no idea what is wrong. So please tell me what the secret trick is to get regex to work like it is supposed to in every other piece of software on earth.

0 Kudos
1 Solution

Accepted Solutions
AlfredBaldenweck
MVP Regular Contributor

It doesn't like it when you have text after the zip.

So, any spaces, any letters, etc. 

I fixed it in my test data by getting rid of the $.

I also got rid of the .*, since it ends up grabbing any text in front.

def extract(address):
    import re
    postal_code = re.search(r'(\d{5}(\-\d{4})?)', address).group(0)
    return postal_code

AlfredBaldenweck_0-1702321618828.png

 

 

View solution in original post

0 Kudos
3 Replies
AlfredBaldenweck
MVP Regular Contributor

Dumb question, but are they both text fields?

It worked fine for me when both were text. 

AlfredBaldenweck_0-1702320367363.png

 

 

0 Kudos
ccowin_odfw
Frequent Contributor

Yes, both are Text Fields that's helpful though. Thought I was going crazy.

0 Kudos
AlfredBaldenweck
MVP Regular Contributor

It doesn't like it when you have text after the zip.

So, any spaces, any letters, etc. 

I fixed it in my test data by getting rid of the $.

I also got rid of the .*, since it ends up grabbing any text in front.

def extract(address):
    import re
    postal_code = re.search(r'(\d{5}(\-\d{4})?)', address).group(0)
    return postal_code

AlfredBaldenweck_0-1702321618828.png

 

 

0 Kudos