Menu Close

Escaping Special Characters Regex(regular expressions) in Python..FTC

Python makes regular expressions available through theΒ re module.

Special characters (like the character class brackets [ and ] below) are not matched literally:

import re
match = re.search(r'[b]', 'a[b]c')
print(match.group())
# Output:  'b'

By escaping the special characters, they can be matched literally:

import re
match = re.search(r'\[b\]', 'a[b]c')
print(match.group())
# Output:  '[b]'

The re.escape() function can be used to do this for you:

import re
print(re.escape('a[b]c'))
# Output:  'a\\[b\\]c'

match = re.search(re.escape('a[b]c'), 'a[b]c')
print(match.group())
# Output:  'a[b]c'

The re.escape() function escapes all special characters, so it is useful if you are composing a regular expression based on user input:

import re
username = 'A.C.' # suppose this came from the user
temp = re.findall(r'Hi {}!'.format(username), 'Hi A.C.! Hi ABCD!')
print(temp)
# Output:  ['Hi A.C.!', 'Hi ABCD!']

temp = re.findall(r'Hi {}!'.format(re.escape(username)), 'Hi A.C.! Hi ABCD!')
print(temp)
# Output:  ['Hi A.C.!']

ILLUSTRATION USING PYTHON CLI

For the first part in using regular expressions and matching the string
you can visit this link –>   πŸ‘‡ πŸ‘‡
Matching the beginning of a string (Regex) Regular Expressions in python

The re.search() method takes a regular expression pattern and a string and searches for that pattern within the string. If the search is successful, search() returns a match object or None otherwise.
For the second part in using regular expression and searching the string
visit –> Searching – Regular Expressions (Regex) in Python

Replacing Strings using Regex Python
Replacements can be made on strings using re.sub. πŸ‘‡ πŸ‘‡ πŸ‘‡
Replacing Strings using Regular Expression Regex in Python..-FcukTheCode.com
Replacing strings and Using group references Replacements with a small number of groups can be made.