Regex in Python
What:
Regex stands for Regular expression. It is a sequence of characters that forms some pattern. These patterns can be used to search or match strings. Python has 're' module for applying regex on strings. Regex is build up of some special characters and alphabets.
Why:
Regex is useful, when we have to do parsing on a lot of data. A simple character can match a whole string; sounds already fascinating. The statement will become more clear after the article.
How:
The Python re module has some functions, that can be used for pattern matching and searching using regex:
First of all, on the top of your python script do this:
set some variables:
First of all, on the top of your python script do this:
import re
set some variables:
1. re.match
This function is used to match some pattern at the beginning of a string. It returns a match object. Which contains many attributes, we can see them using, dir method. The attribute group method used in following example displays the string matched by pattern, grouping is discussed in the post later.
example:
Output:
example:
Output:
2.re.search:
Similar to match, but differ in the manner that, it searches throughout the string and not just beginning.
example: Output:
example: Output:
Difference between match and search:
Try this:
example: Output: match and search both return an object instance. So we use group method to print the matched string.
example: Output: match and search both return an object instance. So we use group method to print the matched string.
3. re.findall:
It finds all the occurences of the pattern and returns a list of them.
example: Output: Above functions are for matching patterns. 're' also have function for replacing text with another.
example: Output: Above functions are for matching patterns. 're' also have function for replacing text with another.
4. re.sub:
It finds the part of string which matches the pattern and replace it with a string provided in arguments as replacement.
example: Output:
python standard library documentation
for list of patterns available:
http://www.lleess.com/2013/03/python-regular-expression.html
Few tools for testing regex:
ExtendsClass
regularexpressions101
python-regex: Not live anymore
example: Output:
References:
http://www.regular-expressions.info/python.htmlpython standard library documentation
for list of patterns available:
http://www.lleess.com/2013/03/python-regular-expression.html
Few tools for testing regex:
Comments
Leave a comment