find zip codes in a string using regex in python

Here's an example implementation of finding zip codes in a string using regular expression in Python:

main.py
import re

# Create a sample string containing zip codes
sample_string = "123 Main St, Anytown, USA 12345"

# Define the regex pattern for matching zip codes
zip_pattern = r"\b\d{5}\b"

# Use re.findall() method to return all matched patterns
zip_codes = re.findall(zip_pattern, sample_string)

# Print the zip codes found in the string
print(zip_codes)
354 chars
14 lines

In this code, we create a sample string containing zip codes. We then define a regex pattern to match 5-digit zip codes. We use the re.findall() method to return all matched zip code patterns in the string. Finally, we print the zip codes found in the string.

gistlibby LogSnag