Home Backend Development Python Tutorial Seven Python regular expression usage examples

Seven Python regular expression usage examples

Apr 07, 2017 am 10:46 AM

As a concept, regular expressions are not unique to Python. However, there are still some minor differences in the actual use of regular expressions in Python.

This article is part of a series of articles about Python regular expressions. In this first article in this series, we will focus on how to use regular expressions in Python and highlight some of the unique features of Python.

We will introduce some methods of searching and finding strings in Python. Then we'll discuss how to use grouping to process the sub-items of the matching objects we find.

The module for regular expressions in Python that we are interested in using is usually called 're'.

Seven Python regular expression usage examples

1. Primitive type string in Python

The Python compiler uses 'Seven Python regular expression usage examples' (backslash) to represent characters Escape characters in string constants.

If the backslash is followed by a string of special characters recognized by the compiler, then the entire escape sequence will be replaced with the corresponding special character (for example, 'Seven Python regular expression usage examplesn' will be replaced by the compiler with a newline character ).

But this poses a problem for using regular expressions in Python, because backslashes are also used in the 're' module to escape special characters in regular expressions (such as * and +) .

The mixture of the two means that sometimes you have to escape the escape character itself (when the special character is recognized by both Python and the regular expression compiler), but at other times you This is not necessary (if the special characters are only recognized by the Python compiler).

Instead of focusing on figuring out how many backslashes are needed, we can use raw strings instead.

Primitive type strings can be created simply by adding an 'r' character before the double quotes of an ordinary string. When a string is of primitive type, the Python compiler does not attempt any substitutions. Essentially, you are telling the compiler not to interfere with your string at all.

Seven Python regular expression usage examples

Using regular expressions to find in Python

're' module provides several methods for input strings Make exact inquiries. The methods we will discuss are:


Seven Python regular expression usage examples

Each method accepts a regular expression and a string to find a match. Let's look at each of these methods in more detail to understand how they work and how they differ.

2. Use re.match to search – matching starts

Let’s take a look at the match() method first. The way the match() method works is that it only finds a match if the beginning of the string being searched matches the pattern.

For example, if you call the math() method on the string 'dog cat dog', the search pattern 'dog' will match:

Seven Python regular expression usage examples

We will The group() method will be discussed more later. For now, we just need to know that we called it with 0 as its argument, and that the group() method returns the matching pattern found.

I have skipped the returned SRE_Match object for now, we will discuss it soon.

However, if we call the math() method on the same string, looking for the pattern 'cat', no match will be found.

Seven Python regular expression usage examples

3. Use re.search to find – match any position

The search() method is similar to match(), but search The () method does not restrict us from looking for matches only from the beginning of the string, so looking for 'cat' in our example string will find a match:

Seven Python regular expression usage examples

However The search() method stops when it finds a match, so searching for 'dog' using the searc() method in our example string will only find the first occurrence of it.

Seven Python regular expression usage examples

4. Use re.findall - all matching objects

The search method I use most in Python so far is findall() method. When we call the findall() method, we can very simply get a list of all matching patterns instead of getting the match object (we will discuss the match object more next). For me it's simpler. Calling the findall() method on the example string we get:

Seven Python regular expression usage examples

5. Use the match.start and match.end methods

So, what is the 'match' object" previously returned to us by the search() and match() methods?

Unlike simply returning the matching part of the string, the "matching object" returned by search() and match() is actually a wrapper class for matching substrings.

Earlier you saw that I can get the matched substring by calling the group() method, (we will see in the next section that the match object is actually very useful when dealing with grouping problems), but the match object is still Contains more information about matching substrings.

For example, the match object can tell us where the matched content begins and ends in the original string:

Seven Python regular expression usage examples

Knowing this information is sometimes very useful.

6. Group by numbers using mathch.group

As I mentioned before, the match object is very handy for handling grouping.

Grouping is the ability to locate specific substrings of an entire regular expression. We can define a group as part of the entire regular expression, and then locate the matched content of this part separately.

Let’s see how it works:

Seven Python regular expression usage examples

The string I just created looks like one taken from someone’s address book A fragment. We can match this line with a regular expression like this:

Seven Python regular expression usage examples

By surrounding the regular expression with parentheses (the characters '(' and ')') We can group content into specific sections and then process these subgroups individually.

Seven Python regular expression usage examples

These groups can be obtained by using the group() method of the group object. They can be located by the numerical order in which they appear from left to right in the regular expression (starting from 1):

Seven Python regular expression usage examples

The reason why the ordinal number of a group starts from 1 is because The 0th group is reserved to store all matching objects (we saw it when we studied the match() method and search() method before).

Seven Python regular expression usage examples

7. Use match.group to group by alias

Sometimes, especially when a regular expression has many groups, by group Positioning based on the order of appearance will become unrealistic. Python also allows you to specify a group name through the following statement:

Seven Python regular expression usage examples

We can still use the group() method to get the contents of the group, but this time we have to use what we have Specify the group name instead of the number of digits of the group used previously.

Seven Python regular expression usage examples

This greatly enhances the clarity and readability of the code. You can imagine that as regular expressions become more complex, it becomes more and more difficult to understand what a group captures. Naming your groups will clearly tell you and your readers your intentions.

Although the findall() method does not return a grouped object, it can also use grouping. Similarly, the findall() method will return a collection of tuples, where the Nth element in each tuple corresponds to the Nth grouping in the regular expression.

Seven Python regular expression usage examples

However, naming the group does not apply to the findall() method.

In this article we introduced some basics of using regular expressions in Python. We learned about the primitive string type (and how it can help you solve some of the headaches of using regular expressions). We also learned how to use the match(), search(), and findall() methods to perform basic queries, and how to use grouping to handle subcomponents of matched objects.

As always, if you want to see more on this topic, the official Python documentation for the re module is a great resource.

In future articles, we will discuss the application of regular expressions in Python in more depth. We'll take a more comprehensive look at match objects, learn how to use them to perform substitutions within strings, and even use them to parse Python data structures from text files.

The above is the detailed content of Seven Python regular expression usage examples. For more information, please follow other related articles on 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
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles