Last active
December 25, 2019 15:01
-
-
Save yoki/3cfef61b90f9184f855adbab63ead9f9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
match.py | |
replace.py | |
search.py |
This file contains hidden or 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
############################ | |
# Test Match | |
############################ | |
## Regex Match | |
text2 = 'Nov 27, 2012' | |
import re | |
if re.match(r'\d+/\d+/\d+', text1): print('yes') | |
#=> yes | |
# you can compile the regex for speed | |
datepat = re.compile(r'\d+/\d+/\d+') | |
if datepat.match(text1): print('yes') | |
#=> yes | |
## Simple search | |
text = 'yeah, but no, but yeah, but no, but yeah' | |
# Exact match | |
text == 'yeah' #=> False | |
# Match at start or end | |
text.startswith('yeah') #=> True | |
text.endswith('no') #=> False | |
# Search for the location of the first occurrence | |
text.find('no') #=> 10 |
This file contains hidden or 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
############################ | |
# Replace | |
############################ | |
# regex | |
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' | |
re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text) | |
#=> 'Today is 2012-11-27. PyCon starts 2013-3-13.' | |
# simple | |
text = 'yeah, but no, but yeah, but no, but yeah' | |
text.replace('yeah', 'yep') | |
#=> 'yep, but no, but yep, but no, but yep' | |
This file contains hidden or 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
########################### | |
## Extract mathed elements | |
############################ | |
# extract sub patterns | |
m = datepat.match('11/27/2012') | |
( m.group(0), m.group(1), m.group(2), m.group(3)) | |
#=> ('11/27/2012', '11', '27', '2012') | |
>>> month, day, year = m.groups() # month, day, year is defined | |
# Find all matches (notice splitting into tuples) | |
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' | |
datepat.findall(text) #=> [('11', '27', '2012'), ('3', '13', '2013')] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment