A RegEx, or Regular Expression is a sequence of characters that defines a search pattern. It is used to check whether a string contains specified search pattern or not. Please see the below mentioned search pattern:
^P....n$
The above search pattern can be used to check whether a string contains six characters which starts with P and ends with n.
Please note that Python has a in-built module re which need to be imported to work with Regular Expression.
In the below example, ^p....n$ search pattern is checked in string called MyString.
import re MyString = "Python" x = re.search("^P....n$", MyString) if(x): print("Pattern found.") else: print("Pattern not found.") MyString = "Python!." x = re.search("^P....n$", MyString) if(x): print("Pattern found.") else: print("Pattern not found.")
Pattern found. Pattern not found.
Metacharacters are the special characters which are interpreted in a different way by RegEx engine. The metacharacters are:
Character | Description | Example |
---|---|---|
[] | To specify a set to characters | "[a-z]" |
. | To specify any character except new line | "He..o" |
^ | To specify starts with character(s) | "^Hello" |
$ | To specify ends with character(s) | "World$" |
* | To check zero or more occurrences of specified character(s) | "Helx*" |
+ | To check one or more occurrences of specified character(s) | "Helx+" |
{} | To check the specified number of occurrences of specified character(s) | "Hel{2}" |
? | To check zero or one occurrences of specified character(s) | "He?l" |
| | To specify either or | "go|come" |
() | To group sub-patterns | "(x|y|z)abc" |
\ | To escape various characters including all metacharacters | "\$" |
Metacharacters are the special characters which are interpreted in a different way by RegEx engine. The metacharacters are:
Character | Description | Example |
---|---|---|
\A | To specify a set to characters | "[a-z]" |
\b | To specify any character except new line | "He..o" |
\B | To specify starts with character(s) | "^Hello" |
\d | To specify ends with character(s) | "World$" |
\D | To check zero or more occurrences of specified character(s) | "Helx*" |
\s | To check one or more occurrences of specified character(s) | "Helx+" |
\S | To check the specified number of occurrences of specified character(s) | "Hel{2}" |
\w | To check zero or one occurrences of specified character(s) | "He?l" |
\W | To specify either or | "go|come" |
\Z | To group sub-patterns | "(x|y|z)abc" |
\ | To escape various characters including all metacharacters | "\$" |