How to use special characters in Python Regular Expression?

PythonServer Side ProgrammingProgramming

From Python documentation

Non-special characters match themselves. Special characters don't match themselves −

\
 Escape special char or start a sequence.
.
Match any char except newline, see re.DOTALL
^
Match start of the string, see re.MULTILINE
 $  
Match end of the string, see re.MULTILINE
[ ]
Enclose a set of matchable chars
R|S
 Match either regex R or regex S.
()
Create capture group, & indicate precedence


After '[', enclose a set, the only special chars are −

]
End the set, if not the 1st char
-
A range, eg. a-c matches a, b or c
^
Negate the set only if it is the 1st char

    

Quantifiers (append '?' for non-greedy) −

{m}
Exactly m repetitions
 {m,n}
From m (default 0) to n (default infinity)
*
0 or more. Same as {,}
+
1 or more. Same as {1,}
?
0 or 1. Same as {,1}

  

raja
Published on 11-Jan-2018 12:40:36
Advertisements