1import re
2
3# Regex Cheat sheet : https://www.dataquest.io/blog/regex-cheatsheet/
4# Regex python tester : https://pythex.org/
5# re doc : https://docs.python.org/3/library/re.html
6
7text = "i like train"
8reg = r"[a-c]" #the group of char a to c
9
10if re.match(reg, text): #Check if regex is correct
11 print(text)
12else:
13 print("Not any match")
1import re
2
3# The string you want to find a pattern within
4test_string = 'Hello greppers!'
5
6# Creating a regular expression pattern
7# This is a simple one which finds "Hello"
8pattern = re.compile(r'Hello')
9
10# This locates and returns all the occurences of the pattern
11# within the test_string
12match = pattern.finditer(test_string)
13
14# Outputs all the ocurrences which were returned as
15# as match objects
16for match in matches:
17 print(match)
18
19
1import re
2
3pattern = '^a...s$'
4test_string = 'abyss'
5result = re.match(pattern, test_string)
6
7if result:
8 print("Search successful.")
9else:
10 print("Search unsuccessful.")
11
11. A fixed string -> abc123
22. Arbitrary repetition -> a*b ( "*" means that you can have an arbitrary
3 number (possibly 0) of the previous char
43. Repeat character at least once -> a+b # ab, aaaab
54. Repeat character at most once -> a?b # b, ab
65. Repeat a character a fixed number of timers -> a{5} # aaaaa
76. Repeat a pattern a fixed number of times -> (a*b){3} # baabab, ababaaaab
87. Repeat a character or pattern a variable number of times -> a{2,4} # aa, aaa, aaaa
98. Choice of several characters -> [ab]c # ac, bc
109. Arbitrary mixture of several characters -> [ab]*c # c, aac, abbac
1110. Ranges of characters -> [A-H][a-z]* # Aasdfalsd, Hb, G
1211. Characters OTHER than particular one -> [^AB] # C, D
1312. Choice of several expressions -> Dr|Mr|Ms|Mrs # Dr, Mr, Mrs, Ms
1413. Nesting expressions -> ([A-Z][a-z][0-9])* # A, AzSDFcvfg
1514. Start of a line -> ^ab
1615. End of a line -> ab$
17
18#Type of pattern
191. Special characters -> \[ # [
202. Any charactter 'except' newline -> . # a, *, -
213. Nongreedy evaluation -> <.*>? # <h1></h2 name = "foo">
224. Whitespace -> \s
1# pip install regex
2import re
3# simple find all
4sample = "Nothing lasts... but nothing is lost"
5found = re.findall("thing", sample)
6print(found)