Large topic – somewhat more advanced than ‘basic programming’, but worth a digression. (reference)
What if we are looking for some number, but we don’t know what number?
import re
bool(re.search('[0-9]', 'Plan 9'))
Pattern | Description |
---|---|
^ |
Beginning of line |
$ |
End of line |
. |
Any single character except newline |
[...] |
Any single character in brackets |
[^...] |
Any single character not in brackets |
re* |
0 or more occurrences of preceding expression |
re+ |
1 or more occurrence of preceding expression |
re? |
0 or 1 occurrence of preceding expression |
re1|re2 |
match re1 or re2 |
() |
grouping |
import re
x = "(Smith, John), (Schmo, Joe)"
re_pat = "\(([A-Z][a-z]+), ([A-Z][a-z.]*)\)"
print(re.sub(re_pat,"(\\2 \\1)",x))
## (John Smith), (Joe Schmo)
+
or (
and not have them interpreted in their regular-expression sense), you need to use a backslash \
as an “escape” character: for example, "a\+b"
will look for the letter a
, followed by a plus sign, followed by the letter b
– not one or more a
s, followed by a b
(xkcd)