Python Regular Expressions: Difference between revisions
Jump to navigation
Jump to search
Line 1: | Line 1: | ||
=External= | =External= | ||
* https://docs.python.org/3/library/re.html | * https://docs.python.org/3/library/re.html | ||
* https://docs.python.org/3/howto/regex.html#regex-howto | |||
=Internal= | =Internal= | ||
=Overview= | =Overview= |
Revision as of 21:10, 15 March 2022
External
Internal
Overview
A regular expression is specified with r"..."
Metacharacters
Replacing Regular Expression Occurrences
import re
s = "this is a {{color}} car"
print(re.sub(r"{{color}}", 'blue', s))
Strip quotes:
s = "'something'"
re.sub(r"'$", '', re.sub(r"^'", '', s))
Capture groups and use them in the replacement:
s = 'this is red'
s2 = re.sub(r'^(this is).*$', '\\1 blue', s)
assert 'this is blue' == s2
To dynamically build a regular expression, use rf'...'
s = 'this is a red string'
color = 'red'
s2 = re.sub(rf'{color}', 'blue', s)
assert 'this is a blue string' == s2
Match a new line:
r'\n'
Match not a new line:
r'[^\n]'
Match a Pattern and Pick Up Groups
match = re.search(pattern, string)
if match:
process(match)