Regex in Python
Regular expression is very cool for string manipulation and other stuff. In python for this purpose regex module is provided.
Get aaron’s stories in your inbox
Join Medium for free to get updates from this writer.
Following are some rules to make a regex :-
^denotes start of the string.$denotes end of the string.*denotes zero or more repetition of re.+denotes one or more repetition of re..matches for everything except new line.?matches zero or one repetition of re.{a}matches exactly a repetition of the re.{a, b}matches repetition of the re in range of a to b.[]is used to match a set of characters.\is used to escape special characters.\\is used to match\in re.
Now let’s make regex for a simple string which is having only lowercase characters-
re = "[a-z]" # matches character from a to z.Let’s make regex for a string having following conditions:-
- first character should be lowercase alphabate.
- second character should be in the range of
atozor0to9or:. - then there should be a forward slash.
- after that one or more repetitions of
atozor0to9. - then there should be backslash.
Now following the rules described above the regex for upper condition will be
re = "[a-z]{1}[a-z0-9:]{1}/[a-z0-9]+\\"Now coming to python regex module
import re# define a pattern to match
pattern = "[a-z]"# string to check with
string = "abcd"p = re.compile(pattern)
result = p.match(string)# result will be none if the string is not matched
Compile and match can be done in one line as well by
result = re.match(pattern, string)But in this pattern will be compiled on every call to match. If we want to check same pattern on several string then first option is time efficient.
This was very basic introduction to regex.
For more- click here









