Last active
August 12, 2016 12:57
-
-
Save tchajed/779a436ae7210b2082e1b86fbb9feb89 to your computer and use it in GitHub Desktop.
Python re examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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