Sets
Expressions | Explanations |
---|---|
[abc] |
Matches either a, b, or c. It does not match abc. |
[a-z] |
Matches any alphabet from a to z. |
[A-Z] |
Matches any alphabets in capital from A to Z |
[a\-p] |
Matches a, -, or p. It matches – because \ escapes it. |
[-z] |
Matches – or z |
[a-z0-9] |
Matches characters from a to z or from 0 to 9. |
[(+*)] |
Special characters become literal inside a set, so this matches (, +, *, or ) |
[^ab5] |
Adding ^ excludes any character in the set. Here, it matches characters that are not a, b, or 5. |
\[a\] |
Matches [a] because both parentheses [ ] are escaped |
Examples:
Python3
import re print (re.search(r "[^abc]" , "abcde" )) print (re.search(r "[a-p]" , "xenon" )) |
Output:
<re.Match object; span=(3, 4), match='d'>
<re.Match object; span=(1, 2), match='e'>
Explanation:
In the first example, [^abc] will search for anything except a, b and c, so regex will match the first character which is not a or b or c and will print out that match. Since abcde contains d as its first match that is neither a nor b nor c, it will print out that match. So match would be (‘d’) and its position would be (3,4)
In the second example, [a-p] will search for the character between a to p. In xenon the first word between a-p is e it will print out that search. So match would be (‘e’) and its position would be (1,2)
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