Regex: what is it?
A regular expression is a text string used to describe a search pattern.
# Regex # find a particular pattern in a String s = 'Waz D: 5 l gu l: 5 GrinVe: 3 P LUK: 2 Cubbi: 1 2 nd dok: 1 maf 74: 1 abr12: 1 Waza D: 5' import re # \w find something starting with a letter or a number # [\w\s]+ followed by any number of letter and space # : followed by a : # \s[0-9] and a space and a number x = re.findall(r"\w[\w\s]+:\s[0-9]", s) print(*x, sep="\n")
In the previous code the goal was to find a name followed by ‘:’ a space and a number and to put them in a list. We use the ‘re’ module of Python. After we import it, we define the string ‘s’ where we have to find the piece of the string that behave like the pattern. The pattern is made as follow:
\w ................ a letter or a number [\w\s]+ .......... as many letters or numbers following the letter/number : ................... a column \s[0-9] ........... a space and then a number
Video explanation