Here are a few most common examples:
#!/usr/bin/env python
import re
#
# search a substring in a string
#
pattern = "A.C."
string = "xxABCDxx"
matchobj = re.search( pattern, string)
if( matchobj):
print( matchobj.start()) # -> 2
#
# divide a string into groups
#
patt = re.compile( "A(\d*)B(\d*)C(\d*)")
res = patt.match( "A1B12C123")
print( res.group(1),res.group(2),res.group(3)) # -> 1 12 123
Metacharacters:
\ | ( ) [ { ^ $ * + ?
Pattern syntax:
. any character but newline |
^,$ start/end of line |
* zero or more occ. of the prec. char. or group |
+ one or more occ. of the prec. char. or group |
? zero or one occ. of prec. char. or group (ungreedy) |
[a-z] range fo chars, [abc] group of chars |
[^...] anything but range fo chars. |
\ escape character |
\t tab |
\n newline |
\\ backslash |
\b start or end of word |
\B next string not in word |
\< start of word |
\> end of word |
\d digit |
\D non-digit |
\s a whitespace character |
\S a non-whitespace character |
\w any word charcter |
\W any non-word character |
\| multiple patterns |
(...) group
|