-
-
Notifications
You must be signed in to change notification settings - Fork 519
/
regex.py
54 lines (39 loc) · 1.94 KB
/
regex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""
Using regular expressions is a robust way to search for text. Implementing
them is difficult but Python provides a package for us to use them easily.
This module shows a few examples of how to use the `re` package to search
predefined text snippets stored in module-level constants.
"""
import re
# Module-level constants
_TEXT_HELLO = "World Hello Hello"
_TEXT_NAMES = "John, Jane"
_TEXT_ABC123 = "abc123"
_TEXT_BYE = "Bye for now"
_TEXT_EMAILS = "My work email is kayode@dodo.ng while nerdthejohn@yahoo.com is personal"
def main():
# Running `search` with "Hello" has a match for first Hello
assert re.search(r"Hello", _TEXT_HELLO).start() == 6
# Running `search` with "Hello$" has a match for last Hello
assert re.search(r"Hello$", _TEXT_HELLO).start() == 12
# Running `search` with "(Hello) (Hello)" has matches for Hello
assert re.search(r"(Hello) (Hello)", _TEXT_HELLO).groups() == ("Hello", "Hello")
# Running `findall` with "Hi \w+" has a list of strings
assert re.findall(r"\w+", _TEXT_NAMES) == ["John", "Jane"]
# Running `findall` with "[a-z]+@[a-z]+\.[a-z]+" has a list of email strings
assert re.findall(r"[a-z]+@[a-z]+\.[a-z]+", _TEXT_EMAILS) == ["kayode@dodo.ng", "nerdthejohn@yahoo.com"]
# Running `match` with "[123]+" has nothing
assert re.match(r"[123]+", _TEXT_ABC123) is None
# Running `match` with "[abc]+" has a match for abc
assert re.match(r"[abc]+", _TEXT_ABC123).group(0) == "abc"
# Running `fullmatch` with "[\w]+" has nothing
assert re.fullmatch(r"[\w]+", _TEXT_BYE) is None
# Running `fullmatch` with "[\w ]+" has a full match
assert re.fullmatch(r"[\w ]+", _TEXT_BYE).group(0) == _TEXT_BYE
# To learn more about regular expressions:
# https://en.wikipedia.org/wiki/Regular_expression
# https://github.com/ziishaned/learn-regex
# To play around with regular expressions in the browser:
# https://regex101.com
if __name__ == "__main__":
main()