Home Backend Development Python Tutorial Python's re module regular expression operations

Python's re module regular expression operations

Mar 02, 2017 pm 04:08 PM

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 0x00A9A988>
>>> re.match("c", "cabcdef")
<_sre .SRE_Match object at 0x00A9AB80>
>>> re.search("c","cabcdef")
<_sre.SRE_Match object at 0x00AF1720>
>>> patterm = re.compile("c")
>>> patterm.match("abcdef")
>>> patterm.match("abcdef",1)
>> ;> patterm.match("abcdef",2)
<_sre.SRE_Match object at 0x00A9AB80>

##3.Module content

re.compile(pattern, flags=0)


Compile the regular expression and return the RegexObject object, and then you can call match() and search() through the RegexObject object method.


prog = re.compile(pattern)

result = prog.match(string)

followed by


result = re .match(pattern, string)


is equivalent.


The first method can realize the reuse of regular expressions.


re.search(pattern, string, flags=0)

Search in the string to see if it can match the regular expression. Returns a _sre.SRE_Match object, or None if no match is found.


re.match(pattern, string, flags=0)

Whether the beginning of the string can match the regular expression. Returns a _sre.SRE_Match object, or None if no match is found.


re.split(pattern, string, maxsplit=0)

Split the string through regular expressions. If you enclose the regular expression in parentheses, the matching string will also be included in the list and returned. maxsplit is the number of separations, maxsplit=1 separates once, the default is 0, and there is no limit on the number of times.


>>> re.split('\W+', 'Words, words, words.')

['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)

Note: I used Python is 2.6. Looking at the source code, I found that split() does not have the flags parameter. It was added in 2.7. I have found this problem more than once. The official documentation is inconsistent with the source code. If you find an abnormality, you should go to the source code to find the reason.


If there is a match at the beginning or end of the string, the returned list will start or end with an empty string.


>>> 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!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

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.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles