Skip to content

Instantly share code, notes, and snippets.

@tchajed
Last active August 12, 2016 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tchajed/779a436ae7210b2082e1b86fbb9feb89 to your computer and use it in GitHub Desktop.
Save tchajed/779a436ae7210b2082e1b86fbb9feb89 to your computer and use it in GitHub Desktop.
Python re examples
import re
# match requires the entire string to match, while search will
# find a partial match
assert re.match("\d+", "123")
assert not re.match("\d+", "hello 123")
assert re.search("\d+", "123")
assert re.search("\d+", "hello 123")
import re
# compiled regexes have match and search methods
# Note that Python has a compile cache stored in the re module
# for recently used regexes, so a program with a few static regexes
# need not compile for performance. Nonetheless it can improve
# readability.
# this example also demonstrates numbered groups
tuple_re = re.compile("\(" +
"(.*?)" + # first element
",\s*" + # separator (comma followed by whitespace)
"(.*?)" + # second element
"\)")
def tuple(s):
m = tuple_re.match(s)
# get groups by number (0 is entire match as usual)
return (m.group(1), m.group(2))
assert tuple("(1,2)") == ("1","2")
assert tuple("( abc, def )") == (" abc", "def ")
import re
# Named capture groups can be retrieved by name. The value is
# None if the capture group does not actually match anything.
def keyval(s):
m = re.match("(?P<key>.*):(?P<val>(?P<header>.)?.*)", s)
if m is None:
return None
return (m.group("key"), m.group("val"), m.group("header"))
assert keyval("foo:bar") == ("foo", "bar", "b")
assert keyval("foo:") == ("foo", "", None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment