Introduction

Untitled

Python has module named re that is used to regular expression in Python. We can import this module with the use of import statement.

For example: Importing re module with Python.

re functions

re.findall

import re

# A sample text string where regular expression
# is searched
string = """Hello my student id is 923472387 and 
						my friend's number student id is 234130324"""

# A sample regular expression to find digits.
regex = '\\d+'

match = re.findall(regex, string)
print(match)
['923472387', '234130324']

re.findall( ) : return all suitability pattern that is not overlap into string, as string list. String is scanned from left to right, and the suitability is returned in the list that has been founded.

+ - Plus

Plus symbol (+) matches with one or more possible appearance of regular expression before symbol +. For example:

For example: Finding all appearances of pattern.

re.compile

# Example
import re

# compile() creates regular expression
# character class [a-e]
# which is equivalent to [abcde]
# class [abcde] will match with string with
# 'a', 'b', 'c', 'd', 'e'.
p = re.compile('[a-e]'

re.compile( ) where regular expression is compiled to be pattern object, that has methods for various operation such as searching suitability of pattern or commit string substitution.

# Example
import re

# compile() creates regular expression
# character class [a-e]
# which is equivalent to [abcde]
# class [abcde] will match with string with
# 'a', 'b', 'c', 'd', 'e'.
p = re.compile('[a-e]')

# findall() searches for the Regular Expression
# and return a list upon finding
print(p.findall("Aye, said Mr. Gibeson Stark"))