import re
import sys
text = 'The quick brown fox jumped over the lazy black bear.'
three_letter_word = '...'
pattern_re = re.compile(three_letter_word); pattern_re
re.compile(r'...', re.UNICODE)
re_search = re.search('..own', text)
if re_search:
# Print the search results
print(re_search.group())
brown
re.match() is for matching ONLY the beginning of a string or the whole string For anything else, use re.search
re_match = re.match('..own', text)
if re_match:
# Print all the matches
print(re_match.group())
else:
# Print this
print('No matches')
No matches
re_split = re.split('e', text); re_split
['Th', ' quick brown fox jump', 'd ov', 'r th', ' lazy black b', 'ar.']
Replaces occurrences of the regex pattern with something else
The "3" references to the maximum number of substitutions to make.
re_sub = re.sub('e', 'E', text, 3); print(re_sub)
ThE quick brown fox jumpEd ovEr the lazy black bear.
[Pp]ython Match "Python" or "python"
rub[ye] Match "ruby" or "rube"
[aeiou] Match any one lowercase vowel
[0-9] Match any digit; same as [0123456789]
[a-z] Match any lowercase ASCII letter
[A-Z] Match any uppercase ASCII letter
[a-zA-Z0-9] Match any of the above
[^aeiou] Match anything other than a lowercase vowel
[^0-9] Match anything other than a digit
ruby? Match "rub" or "ruby": the y is optional
ruby* Match "rub" plus 0 or more ys
ruby+ Match "rub" plus 1 or more ys
\d{3} Match exactly 3 digits
\d{3,} Match 3 or more digits
\d{3,5} Match 3, 4, or 5 digits
^Python Match "Python" at the start of a string or internal line
Python$ Match "Python" at the end of a string or line
\APython Match "Python" at the start of a string
Python\Z Match "Python" at the end of a string
\bPython\b Match "Python" at a word boundary
\brub\B \B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
Python(?=!) Match "Python", if followed by an exclamation point
Python(?!!) Match "Python", if not followed by an exclamation point
python|perl Match "python" or "perl"
rub(y|le)) Match "ruby" or "ruble"
Python(!+|?) "Python" followed by one or more ! or one ?