Last active
October 21, 2019 12:24
-
-
Save matt-dray/a432e98b5cba4fd80d95a5324ee1d248 to your computer and use it in GitHub Desktop.
Basic re module usage to find text strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Import re for working with regular expressions | |
import re | |
# Provide some text to search | |
# 'Hipster ipsum' via https://hipsum.co/ | |
text = "Lorem ipsum dolor amet selfies williamsburg tattooed ethical wolf cloud bread. Cronut marfa heirloom pour-over. Jean shorts aesthetic before they sold out, yr subway tile kale chips occupy. Banjo lomo af, meditation roof party cronut vape glossier." | |
# Search for a specific phrase | |
# Returns a 'match' object | |
# More info here: https://www.w3schools.com/python/python_regex.asp#matchobject | |
x = re.search("Jean shorts", text) | |
print(x) | |
# <_sre.SRE_Match object; span=(112, 123), match='Jean shorts'> | |
x.span() # start and end location of match | |
# (112, 123) | |
# Simpler alternative: return a list containing matches | |
y = re.findall("Jean shorts", text) | |
print(y) | |
# ['Jean shorts'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment