re.subn()

re.subn(pattern, repl, string, count=0, flags=0)

import re

print(re.subn('ub', '-*', 'Subject has Uber booked already'))

t = re.subn('ub', '-*', 'Subject has Uber booked already',
						flags=re.IGNORECASE)
print(t)
print(len(t))

# This will give same output as sub() would have
print(t[0])
('S-*ject has Uber booked already', 1)
('S-*ject has -*er booked already', 2)
2
S-*ject has -*er booked already

re.subn(), subn() is similar with sub() in all aspects, except in the method to give the output. It returns Tuple with calculation of change total and new string, not only string.

re.escape()

re.escape(string)

import re

# escape() returns a string with BlackSlash '\\'
# before every Non-Alphanumeric Character
# In 1st case only ' ', is not alphanumeric
# in 2nd case, ' ', caret '^', '-', '[ ] ', '\\'
# are not alphanumeric
print(re.escape("This is Awesome even 1 AM"))
print(re.escape("I Asked that is this [a-9], he said \\t ^WoW"))
This\\ is\\ Awesome\\ even\\ 1\\ AM
I\\ Asked\\ that\\ is\\ this\\ \\[a\\-9\\],\\ he\\ said\\ \\	\\ \\^WoW

Returning string with all backslashes of non-alphanumeric, it is useful if you want to match arbiter literal string that may have regular expression meta character inside.

re.search()

re.search() this Method returns None (if the pattern is not matched), or re.MatchObject consist of information about the part of string that is suitable. This method stops after the first match, so this is the most suitable to test regular expression more than extracting data.

# A Python program to demonstrate working of re.match().
import re

# Let's use a regular expression to match a date string
# in the form of Month name followed by day number
regex = r"([a-zA-Z]+) (\\d+)"

match = re.search(regex, "I was born on June 24 ")

if match != None:
    # We reach here when the expression "([a-zA-Z]+) (\\d+)"
    # matches the date string

    # This will print [14, 21], since it matches at index 14
    # and ends at 21
    print("Match at index %s, %s" % (match.start(), match.end()))

    # We use group() method to get all the matches and
    # captured groups. The groups contain the matched values
    # In particular:
    # match.group(0) always returns the fully matched string
    # match.group(1), match.group(2), ... return the capture
    # groups in order from left to right in the input string
    # match.group() is equivalent to match.group(0)

    # So this will print "June 24"
    print("Full match: %s" % (match.group(0)))

    # So this will print "June"
    print("Month: %s" % (match.group(1)))

    # So this will print "24"
    print("Day: %s" % (match.group(2)))

else:
    print("The regex pattern does not match.")
Match at index 14, 21
Full match: June 24
Month: June
Day: 24