Python Regular Expressions: Difference between revisions
Jump to navigation
Jump to search
(Created page with "=External= * https://docs.python.org/3/library/re.html =Internal= =Overview= A regular expression is specified with <code>r"..."</code> =Replacing Regular Expression Occurrenc...") |
|||
Line 4: | Line 4: | ||
=Overview= | =Overview= | ||
A regular expression is specified with <code>r"..."</code> | A regular expression is specified with <code>r"..."</code> | ||
=Metacharacters= | |||
{{External|https://docs.python.org/3/library/re.html#regular-expression-syntax}} | |||
=Replacing Regular Expression Occurrences= | =Replacing Regular Expression Occurrences= | ||
{{External|https://docs.python.org/3/library/re.html#text-munging}} | {{External|https://docs.python.org/3/library/re.html#text-munging}} |
Revision as of 21:09, 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)