Python Regular Expressions
Python Regular Expressions
Advertisements
Previous Page
Next Page
Parameter Description
Example
#!/usr/bin/python
import re
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"
When the above code is executed, it produces following result −
Parameter Description
Example
#!/usr/bin/python
import re
if searchObj:
print "searchObj.group() : ", searchObj.group()
print "searchObj.group(1) : ", searchObj.group(1)
print "searchObj.group(2) : ", searchObj.group(2)
else:
print "Nothing found!!"
Example
#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
No match!!
search --> matchObj.group() : dogs
Syntax
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the RE pattern in string with repl,
substituting all occurrences unless max provided. This method returns
modified string.
Example
#!/usr/bin/python
import re
Modifier Description
re.M Makes $ match the end of a line (not just the end of the
string) and makes ^ match the start of any line (not just the
start of the string).
Following table lists the regular expression syntax that is available in Python
−
Pattern Description
a| b Matches either a or b.
(?#...) Comment.
\S Matches nonwhitespace.
\D Matches nondigits.
Character classes
Example Description
Repetition Cases
Example Description
Nongreedy repetition
This matches the smallest number of repetitions −
Example Description
Backreferences
This matches a previously matched group again −
Example Description
Alternatives
Example Description
Anchors
This needs to specify match position.
Example Description