Python Regular Expressions

From NovaOrdis Knowledge Base
Revision as of 21:09, 15 March 2022 by Ovidiu (talk | contribs) (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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

External

Internal

Overview

A regular expression is specified with r"..."

Replacing Regular Expression Occurrences

https://docs.python.org/3/library/re.html#text-munging
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)