April 27, 2018

Regular expression example in Python

Regular expression can be used by "re" module in Python.

This is the example of the "findall()" and "search()" of "re" module.


<Source code>
strValue = "!pple Apple $pple apple Bpple Cpple Dpple 8pple"

f = re.compile("[a-z0-9]+pPLe", re.I)
result = f.findall(strValue)
print result
print

result = f.search(strValue)
print "Span : " + str(result.span())
print "Group : " + result.group()
print result

<Result>
['Apple', 'apple', 'Bpple', 'Cpple', 'Dpple', '8pple']

Span : (6, 11)
Group : Apple
<_sre.SRE_Match object at 0x6ffffe56718>

❑ f = re.compile([Regular expression]) : Input a string of regular expression for filtering.
❑ f.search([String]) : Search one filtered string at [String].It returns _sre.SRE_Match object.
❍ [_sre.SRE_Match object].span() : The index(location) of the filtered data.
❍ [_sre.SRE_Match object].group() : The value of the filtered data.
❑ f.findall([String]) : Search all filtered string at [String]. It returns list.
❑ Flag : DOTALL(S), IGNORECASE(I), MULTILINE(M)