Py: Regex
Py: Regex

Regex cheatSheet

Directory

Todo

  • Exemples en Python (Jupyter)

Liens

tuto regex
analyse d’expressions (premier choix)
analyse d’expressions 2

Basic

Core

abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit char
. Any char
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanum char
\W Any Non-alphanum char
\n a newline
\t a tab
\r carriage return
{m} m Repetitions
{m,n} m to n Repetitions
* 0 or more repetitions
+ 1 or more repetitions
? Optional char
\s Any Whitespace
\S Any Non-whitespace char
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(abcdef) Matches abc or def
\b boundary word/non-word

In python

Match aregex @ start of str:

re.match(pattern,string)

match only if pattern fit all str:

re.fullmatch(pattern,string)

match first pattern found:

re.search(pattern,string)

Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement:

re.sub(pattern, repl, string, count=0, flags=0)

Same as sub, + return the nb of sub made:

re.subn(pattern, repl, string)

Split a string by the occurrences of a pattern:

re.split(pattern, string, maxsplit=0)

Find all occurrences of a pattern in a str:

re.findall(pattern,string)

Return an iterator yielding a match object:

re.finditer()

or each match. Compile a pattern into a RegexObject:

re.compile()

Clear the regular expression cache:

re.purge()

Backslash all non-alphanumerics in a string:

re.escape()