Home Backend Development Python Tutorial An introduction to regular expressions and their common matching functions in Python

An introduction to regular expressions and their common matching functions in Python

Jul 25, 2023 pm 05:17 PM
python Regular expression (regexp)

/Introduction/

Python has added the re module since version 1.5, which Provides Perl-style regular expression patterns. The re module enables the Python language to have all regular expression functions.

The compile function generates a regular expression object based on a pattern string and optional flag parameters. This object has a series of methods for regular expression matching and replacement.

The re module also provides functions that are identical to these methods. These functions take a pattern string as their first argument.


##/re.match function/

re.match attempts to match a pattern from the starting position of the string. If the matching is not successful at the starting position, match() will return none. The syntax is as follows:

re.match(pattern, string, flags=0)
Copy after login

"pattern" matches the regular expression "string" and the string "flags" flag to match.

If the match is successful, the re.match method returns a matching object, otherwise it returns None.

We can use group(num) or groups() matching object function to get the matching expression.

group(num=0) 匹配的整个表达式的字符串,“group()”可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。

下图是个实际例子:

An introduction to regular expressions and their common matching functions in Python

输出结果如下图所示:

An introduction to regular expressions and their common matching functions in Python


/检索和替换/

Python 的re模块提供了re.sub用于替换字符串中的匹配项。语法如下所示:

re.sub(pattern, repl, string, count=0, flags=0)
Copy after login

参数:

pattern : 正则中的模式字符串。

repl : 替换的字符串,也可为一个函数。

string : 要被查找替换的原始字符串。

count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。

flags : 编译时用的匹配模式,数字形式。

前三个为必参数,后两个为可选参数。

下图是个实际例子:

An introduction to regular expressions and their common matching functions in Python

输出结果如下图所示:

An introduction to regular expressions and their common matching functions in Python


/compile函数/

compile 函数用于编译正则表达式,供match() 和 search() 这两个函数使用。语法格式为:

re.compile(pattern[, flags])
Copy after login

参数:

pattern : 一个字符串形式的正则表达式

flags 可选,表示匹配模式,比如忽略大小写,多行模式等,具体参数为:

re.I 忽略大小写

re.L represents the special character set \w,\W, \b, \B, \s, \S depends on the current environment

re.M More Line pattern

re.S is '.' and any character including newline ('.' does not include newline)

re.U represents the special character set \w,\W, \b, \B, \d, \D, \s, \S and relies on the Unicode character attribute database

re.X To increase readability, ignore spaces and comments after '#'

/regular expression object/

re.RegexObject: re.compile() returns the RegexObject object.

re.MatchObject: group() returns the string matched by RE.

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)

/regular expression modifier - optional flag/

Regular expressions can contain some optional flag modifiers to control the matching patterns. The modifier is specified as an optional flag. Multiple flags can be specified by bitwise OR(|) them. For example, re.I| re.M is set to I and M flags:

##re.I

Make the match case-insensitive

re.L

Do localization recognition (locale-aware) matching

re.M

Multiple line matching, affecting ^ and $

re.S

# #Make

. match all characters including newlines

re.U

Parses characters according to the

Unicode character set. This flag affects \w, \W, \b, \B.

re. Regular expressions are written to be easier to understand.


/regular expression pattern/

## The pattern string uses special syntax to represent a regular expression Expression:

Letters and numbers represent themselves. Letters and numbers in a regular expression pattern match the same string.

Most letters and numbers have different meanings when preceded by a backslash.

Punctuation marks match themselves only if they are escaped, otherwise they represent a special meaning.

The backslash itself needs to be escaped with a backslash.

Since regular expressions usually contain backslashes, you'd better use raw strings to represent them. Pattern elements (such as r'\t', equivalent to \\t) match the corresponding special characters.

The following table lists the special elements in the regular expression pattern syntax. If you use a pattern and provide optional flags arguments, the meaning of some pattern elements will change.

An introduction to regular expressions and their common matching functions in Python##Regular expression example

Character matching

Example

Description

python

Matches "python".

字符类

An introduction to regular expressions and their common matching functions in Python

/实际应用/

以猫眼电影为例。我们需要获取(电影的名字作者,上映时间)等等都可以用正则表达式来解析。

An introduction to regular expressions and their common matching functions in Python

分析一下,利用正则表达式提取。An introduction to regular expressions and their common matching functions in Python

可以看到我们要的名字在一个a里面,而他们被一个div包裹着。

我们把div想象成一个盒子,可以看到div里面还有一个div 我们可以先找他上面一层的div是一个表单

再找到它的上一层的盒子div
一般来说我们找到前两层就可以找到我们要的结果。如果不对就再找几层。

分析完再实际操作一下:

pattern = re.compile(&#39;<div>.*?title="(.*?)".*?class="star">(.*?)</p>.*?releasetime">(.*?)</p>&#39;,re.S)
Copy after login

    (.*?)表示我们要的内容

(.*?)

里面的主演也是我们要的这样我们就可以得到我们想要得多个数据。


/小结/

1. Regular expressions are suitable for scenarios where multiple data needs to be obtained. It can get the data we want in a faster way.

## 2. This article mainly introduces regular expressions and their basic usage. For specific usage of each character, you can refer to the regular expression series articles in the preface. I hope it can help you learn more. Good understanding of the usage of regular expressions.

The above is the detailed content of An introduction to regular expressions and their common matching functions in Python. 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)

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.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

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.

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.

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.

See all articles