This module provides regular expression matching operations similar to Perl. The same applies to Unicode strings.
Regular expressions use backslash "\" to represent special forms or as escape characters. This conflicts with Python's syntax. Therefore, Python uses "\\\\" to represent regular expressions. "\" in the formula, because if you want to match "\" in the regular expression, you need to use \ to escape it and become "\\", and in Python syntax, you need to escape every \ in the string. So it becomes "\\\\".
Do you find the above writing method troublesome? In order to make regular expressions more readable, Python specially designed raw strings. I need to remind you that in Don't use raw string when writing file paths, there are pitfalls here. Raw string uses 'r' as the prefix of the string, such as r"\n": it represents the two characters "\" and "n" instead of the newline character. This form is recommended when writing regular expressions in Python.
Most regular expression operations can achieve the same purpose as module-level functions or RegexObject methods. And it doesn't require you to compile the regular expression object from the beginning, but you can't use some practical fine-tuning parameters.
1. Regular expression syntax
In order to save space, it will not be described here.
2. The difference between march and search
Python provides two different primitive operations: match and search . Match starts from the starting point of the string, while search (perl default) starts any match from the string.
Note: When the regular expression starts with '^', match and search are the same. match will succeed only if and only if the matched string can be matched from the beginning or can be matched starting from the position of the pos parameter. As follows:
>>> import re
>>> re.match("c", "abcdef")
>>> re .search("c","abcdef")
<_sre.sre_match object at>
>>> re.match("c", "cabcdef")
<_sre .sre_match object at>
>>> re.search("c","cabcdef")
<_sre.sre_match object at>
>>> patterm = re.compile("c")
>>> patterm.match("abcdef")
>>> patterm.match("abcdef",1)
>> ;> patterm.match("abcdef",2)
<_sre.sre_match object at>
##3.Module content
result = prog.match(string)
re.search(pattern, string, flags=0)
re.match(pattern, string, flags=0)
re.split(pattern, string, maxsplit=0)
['Words', 'words', 'words', ' ']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ' , 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', ' words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ' , ', 'words', '...', '']
If the string cannot match, the list of the entire string will be returned.
>>> re.split("a","bbb")
['bbb']
re.findall (pattern, string, flags=0)
Find all substrings matched by RE and return them as a list. The matches are returned in order from left to right. If there is no match, an empty list is returned.
>>> re.findall("a","bcdef")
[]
>>> re.findall (r"\d+","12a32bc43jf3")
['12', '32', '43', '3']
re.finditer(pattern, string, flags= 0)
Find all substrings matched by RE and return them as an iterator. The matches are returned in order from left to right. If there is no match, an empty list is returned.
>>> it = re.finditer(r"\d+","12a32bc43jf3")
>>> for match in it:
print match .group()
re.sub(pattern, repl, string, count=0, flags=0)
Find all substrings matched by RE and use a Different string replacements. The optional argument count is the maximum number of substitutions after a pattern match; count must be a nonnegative integer. The default value is 0 which replaces all matches. If there is no match, the string will be returned unchanged.
re.subn(pattern, repl, string, count=0, flags=0)
has the same effect as the re.sub method, but returns a new A two-tuple of string and number of replacement executions.
re.escape(string)
Escape non-alphanumeric characters in the string
re.purge()
Clear the regular expressions in the cache
4. Regular expression object
re.RegexObject
re.compile() returns the RegexObject object
re.MatchObject
group() returns the object matched by RE String
start() returns the position where the match starts
end() returns the position where the match ends
span() returns a Tuple containing the position of the match (start, end)
5. Compilation flags
Compilation flags allow you to Modify some of the ways regular expressions operate. In the re module, the flag can use two names, one is the full name such as IGNORECASE, and the other is the abbreviation, one-letter form such as I. (If you're familiar with Perl's mode modification, the one-letter forms use the same letter; for example, the abbreviation for re.VERBOSE is re.X.) Multiple flags can be specified by bitwise OR-ing them. For example, re.I | re.M is set to I and M flags:
I
IGNORECASE
Make matching case matching Insensitive; character classes and strings ignore case when matching letters. For example, [A-Z] can also match lowercase letters, and Spam can match "Spam", "spam", or "spAM". This lowercase letter does not take into account the current position.
L
LOCALE
Affects "w, "W, "b, and "B, depending on the current localization set up.
locales is a feature in the C library that is used to assist programming where different languages need to be considered. For example, if you're working with French text, you want to match text with "w+, but "w only matches the character class [A-Za-z]; it doesn't match "é" or "?". If your system is configured appropriately and the locale is set to French, an internal C function will tell the program that "é" should also be considered a letter. Using the LOCALE flag when compiling a regular expression will result in a compiled object that uses these C functions to handle "w"; this will be slower, but will also allow you to use "w+ to match French text.
M
MULTILINE
(^ and $ will not be interpreted at this time; they will be introduced in Section 4.1.)
Use "^" to match only the beginning of the string, while $ will only match the end of the string and the end of the string immediately before a newline (if any). When this flag is specified, "^" matches the beginning of the string and the beginning of each line in the string. Likewise, the $ metacharacter matches the end of the string and the end of each line in the string (directly before each newline).
S
DOTALL
Causes the "." special character to match exactly any character, including newlines; without this flag, "." Matches any character except newline.
X
VERBOSE
This flag makes writing regular expressions easier to understand by giving you a more flexible format. When this flag is specified, whitespace within the RE string is ignored unless the whitespace is within a character class or after a backslash; this allows you to organize and indent REs more clearly. It also allows you to write comments to the RE, which will be ignored by the engine; comments are marked with a "#" symbol, but this symbol cannot come after a string or a backslash.
Finally: If you can use the string method, don’t choose regular expressions, because the string method is simpler and faster.
For more articles related to Python’s re module regular expression operations, please pay attention to the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.