Sitemap
aaron

aaron

Regex in Python

2 min readJan 21, 2017

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 :-

  1. ^ denotes start of the string.
  2. $ denotes end of the string.
  3. * denotes zero or more repetition of re.
  4. + denotes one or more repetition of re.
  5. . matches for everything except new line.
  6. ? matches zero or one repetition of re.
  7. {a} matches exactly a repetition of the re.
  8. {a, b} matches repetition of the re in range of a to b.
  9. [] is used to match a set of characters.
  10. \ 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 a to z or 0 to 9 or :.
  • then there should be a forward slash.
  • after that one or more repetitions of a to z or 0 to 9.
  • 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

--

--