import re
pattern1 = "cat" pattern2 = "bird" string = "dog runs to cat" print(pattern1 in string) print(pattern2 in string)
print(0) print(re.search(pattern1, string)) print(re.search(pattern2, string))
print(1) ptn = r"r[au]n" print(re.search(ptn, string))
print(2) print(re.search(r"r[A-Z]n", string))
print(re.search(r"r[0-9a-z]n", string))
print(3) print(re.search(r"r\dn", string))
print(re.search(r"r\Dn", string))
print(4) print(re.search(r"r\sn", "r\nn,is..."))
print(re.search(r"r\Sn", "run,run"))
print(5) print(re.search(r"^run", "run,is..."))
print(re.search(r"run$", "run,is..."))
print(6) print(re.search(r"run(pig)?", "runs...runpig"))
string = """ dog runs to cat I run to dog. """ print(7) print(re.search(r"^I", string))
print(re.search(r"^I", string, flags=re.M))
print(8) print(re.search(r"ab*", "ab"))
print(re.search(r"ab*", "abbbbb"))
print(9) match = re.search(r"(\d+),Date:(.+)", "ID: 021523,Date:Feb/12/2017") print(match.group())
print(match.group(1))
print(match.group(2))
match = re.search(r"(?P<name>\d+),Date:(?P<id>.+)", "ID: 021523,Date:Feb/12/2017") print(match.group('name'))
print(match.group('id'))
print(10) print(re.findall(r"r[ua]n", "run,ran,run"))
print(re.sub(r"r[au]ns", "catches", "dog runs to cat"))
print(re.split(r"[,;\.\\]", "a;b.c\d;e"))
compiled_re = re.compile(r"r[ua]n") print(compiled_re.search("dog ran to cat"))
|