Python Regular Expression
Some useful symbol which helps to find string pattern –
\d - Matches any decimal digit; this is equivalent to the class [0-9].
\D - Matches any non-digit character; this is equivalent to the class [^0-9].
\s - Matches any whitespace character; this is equivalent to the class [ \t\n\r\f\v].
\S - Matches any non-whitespace character; this is equivalent to the class [^ \t\n\r\f\v].
\w - Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0-9_].
\W - Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0-9_].
How to use RegEx in Python?
Python uses the in-built "re" module. It can import before starting any regular expression with python:
>>> import re
RegEx Methods In Python?
RegEx uses different types of functions to search the pattern from the given strings: Here we learn some important python function
-
findall()
-
search
-
split
-
sub
Use of findall() in RegExp
It returns all matches patterns in the list:
Example:
import re
str = "This is codersarts tutorial"
x = re.findall("is", str)
print(x)
Output:
["is", "is"]
Use of search() in RegExp
It searches the given matches from string and returns it: It returns first matches if more then one matches in the string.
Example:
import re
str = "This is codersarts tutorial"
x = re.search("\s", str) #\s for space
print(x)
Output:
3(position of first space in string)
Use of split() in RegExp
By using this string is split at every matching.
Example:
import re
str = "This is codersarts tutorial"
x = re.split("\s", str) #\s for space search in string
print(x)
Output:
["This", "is", "codersarts", "tutorial"]
Use of sub() in RegExp
It used to replace the matches with the given value in the string.
Example:
import re
str = "This is codersarts tutorial"
x = re.sub("\s", "8", str) #\s for space search in string
print(x)
Output:
This8is8codersarts8tutorial
Read complete python regexp, then please visit python official doc -