Basic Characters
Expression |
Explanations |
---|---|
^ |
Matches the expression to its right, at the start of a string before it experiences a line break |
$ |
Matches the expression to its left, at the end of a string before it experiences a line break |
. |
Matches any character except newline |
a |
Matches exactly one character a |
xy |
Matches the string xy |
a|b |
Matches expression a or b. If a is matched first, b is left untried. |
Example:
Python3
import re print (re.search(r "^x" , "xenon" )) print (re.search(r "s$" , "geeks" )) |
Output:
<re.Match object; span=(0, 1), match='x'>
<re.Match object; span=(4, 5), match='s'>
Explanation:
First import the regex module with the command import re
Then, in the first example, we are searching for “^x” in the word “xenon” using regex. ^ this character matches the expression to its right, at the start of a string. So, ^x will search for character x in the beginning of the string. Since xenon starts with x, it will find the match and will return the match(‘x’) and its position(0,1)
Similarly, in the second example s$ will search for the character s at the end of the string, now since geeks end with s, so it will find the match and will return the match(‘s’) and its position(4,5).
Regex Cheat Sheet – Python
Regex or Regular Expressions are an important part of Python Programming or any other Programming Language. It is used for searching and even replacing the specified text pattern. In the regular expression, a set of characters together form the search pattern. It is also known as the reg-ex pattern. The tough thing about Regex is not learning or understanding it but remembering syntax and how to form patterns according to our requirements.
So, here we have provided a Regex Cheat Sheet containing all the different character classes, special characters, modifiers, sets, etc. which are used in the regular expression.
Table of Content
- Basic Characters
- Quantifiers
- Character Classes
- Sets
- Groups
- Assertions
- Flags