Quantifiers
Expressions | Explanations |
---|---|
+ |
Matches the expression to its left 1 or more times. |
* |
Matches the expression to its left 0 or more times. |
? |
Matches the expression to its left 0 or 1 times |
{p} |
Matches the expression to its left p times, and not less. |
{p, q} |
Matches the expression to its left p to q times, and not less. |
{p, } |
Matches the expression to its left p or more times. |
{ , q} |
Matches the expression to its left up to q times |
Their default searching method is Greedy. But if ? is added to qualifiers (+, *, and ? itself) it will perform matches in a non-greedy manner.
Examples:
Python3
import re print (re.search(r "9+" , "289908" )) print (re.search(r "\d{3}" , "hello1234" )) |
Output:
<re.Match object; span=(2, 4), match='99'>
<re.Match object; span=(5, 8), match='123'>
Explanation:
In the first example, 9+ will search for the number 9 one or more times. Since 289908 contains 9 two times, the regex will match it and will print the match(’99’) and its position(2,4)
In the second example, \d{3} will search for digits exactly 3 times. Since hello1234 have digits, it will match exactly 3 digits which will be encountered first that are 123 and not 4, because {3} will match for exactly 3 digits. So it will print the match(‘123’) and its position(5,8)
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