This article mainly describes how to use regular expressions correctly in the python Regular Expression tutorial, and how to use Python regular expressions to compile the actual application of regular expressions and related code. The following is a detailed introduction of the article.
Now we have read some simple regular expressions. How do we actually use them in Python? The re module provides an interface for the Regular Expression Engine, allowing you to compile REs into objects and use them for matching.
Compile regular expressions
Regular Expressions are compiled into 'regexobject' instances to provide methods for different operations, such as pattern matching search or string replacement.
- #!python>>> import re>>> p = re.compile('ab*')
>>> print p<re.RegexObject instance at 80b4150>re
.compile()
Optional flag parameters are also accepted, which are often used to implement different special functions and syntax changes. We will view all available settings later, but now we only give an example:
- #!python>>> p = re.compile('ab*', re.IGNORECASE)RE
Is sent to re. compile () as a string (). REs is processed as a string because the regular expression is not the core part of the Python language and does not create a specific syntax for it. Applications do not need REs at all, so there is no need to include them to make language descriptions bloated .) The re module is only included by Python in the form of a C extension module, just like the socket or zlib module.
Use REs as a string to ensure the simplicity of the Python language, but the trouble is as mentioned in the title of the next section.
[Edit] the trouble of backslash
In earlier regulations, regular expressions use backslash characters ("\") to represent special formats or allow special characters without calling its special usage. This is in conflict with the same characters in the string that Python plays the same role.
For example, if you want to write a RE to match the string "\ section", it may be in a LATEX file. To judge in the program code, you must first write the string to be matched. Next, you need to add a backslash before all the backslash and metacharacters to cancel their special meaning.
The above is an introduction to how to apply the relevant content in the Python regular expression-python tutorial. I hope you will gain some benefits.