Home Backend Development Python Tutorial Detailed introduction to the re regular expression of python module

Detailed introduction to the re regular expression of python module

Mar 15, 2017 pm 03:18 PM
python regular expression

1. Brief introduction

Regular expression is a small, highly specialized programming language, not python It is a basic and important part of many programming languages. In python, it is mainly implemented through the re module.

Regular expression patterns are compiled into a series of bytecodes and then executed by a matching engine written in C. So what are the common usage scenarios of regular expressions?

For example, specify a rule for the corresponding string set you want to match;

The string set can include an e-mail address, Internet address, phone number, or They are some string sets customized according to needs;

Of course, you can also judge whether a string set conforms to the matching rules we define;

Find the part of the string that matches the rule ;

A series of text processing such as modification and cutting;

......

2. Special symbols and characters (metacharacters )

Here are some common metacharacters, which give regular expressions powerful functionality and flexibility. Table 2-1 lists the more common symbols and characters.

Detailed introduction to the re regular expression of python module

3. Regular expression

1. Use compile()functionCompile regular expression

Because Python code is eventually translated into bytecode and then executed on the interpreter. Therefore, it will be more convenient to pre-compile some regular expressions that are often used in our code. Most of the functions in the

re module have the same names and have the same functions as the methods of compiled regular expression objectsand regular matching objects.

Example:

>>> import re
>>> r1 = r'bugs'                            # 字符串前加"r"反斜杠就不会被任何特殊方式处理,这是个习惯,虽然这里没用到
>>> re.findall(r1, 'bugsbunny')             # 直接利用re模块进行解释性地匹配
['bugs']                         
>>>
>>> r2 = re.compile(r1)                     # 如果r1这个匹配规则你会经常用到,为了提高效率,那就进行预编译吧
>>> r2                                      # 编译后的正则对象
<_sre.SRE_Pattern object at 0x7f5d7db99bb0>
>>>
>>> r2.findall(&#39;bugsbunny&#39;)                 # 访问对象的findall方法得到的匹配结果与上面是一致的
[&#39;bugs&#39;]                                    # 所以说,re模块中的大多数函数和已经编译的正则表达式对象和正则匹配对象的方法同名并且具有相同的功能
Copy after login

The re.compile() function also accepts optional flag parameters, which are often used to implement different special functions and syntax changes. These flags are also available as arguments to most re module functions. These flags can be combined using the operator(|).

Example:

>>> import re
>>> r1 = r&#39;bugs&#39;
>>> r2 = re.compile(r1,re.I)  # 这里选择的是忽略大小写的标志,完整的是re.IGNORECASE,这里简写re.I
>>> r2.findall(&#39;BugsBunny&#39;)
[&#39;Bugs&#39;]
 
# re.S 使.匹配换行符在内的所有字符
# re.M 多行匹配,英雄^和$
# re,X 用来使正则匹配模式组织得更加清晰
Copy after login

For a complete list of flag parameters and usage, please refer to the relevant official documents.

2. Using regular expressions

re module provides a interface for a regular expression engine. Here are some commonly used functions and method.

Matching objects and group() and groups() methods

When dealing with regular expressions, in addition to regular expression objects, there is another object type: matching objects. These are the objects returned by a successful call to match() or search(). Match objects have two main methods: group() and groups().

group() either returns the entire match object or a specific subgroup upon request. groups() simply returns a tuple containing only or all subgroups. If no subgrouping is required, groups returns an empty tuple while group() still returns the entire match. Some function examples below demonstrate this method.

Use the match() method to match a string

The match() function matches the pattern from the beginning of the string. If the match is successful, a match object is returned; if the match fails, None is returned, and the match object's group() method can be used to display the successful match.

Examples are as follows:

>>> m = re.match(&#39;bugs&#39;, &#39;bugsbunny&#39;)     # 模式匹配字符串
>>> if m is not None:                     # 如果匹配成功,就输出匹配内容
...     m.group()
...
&#39;bugs&#39;
>>> m
<_sre.SRE_Match object at 0x7f5d7da1f168> # 确认返回的匹配对象
Copy after login

Use search() to find patterns in a string

search()的工作方式与match()完全一致,不同之处在于search()是对给定正则表达式模式搜索第一次出现的匹配情况。简单来说,就是在任意位置符合都能匹配成功,不仅仅是字符串的起始部分,这就是与match()函数的区别,用脚指头想想search()方法使用的范围更多更广。

示例:

>>> m = re.search(&#39;bugs&#39;, &#39;hello bugsbunny&#39;)
>>> if m is not None:
...     m.group()
...
&#39;bugs&#39;
Copy after login

使用findall()和finditer()查找每一次出现的位置

findall()是用来查找字符串中所有(非重复)出现的正则表达式模式,并返回一个匹配列表;finditer()与findall()不同的地方是返回一个迭代器,对于每一次匹配,迭代器都返回一个匹配对象。

>>> m = re.findall(&#39;bugs&#39;, &#39;bugsbunnybugs&#39;)
>>> m
[&#39;bugs&#39;, &#39;bugs&#39;]
>>> m = re.finditer(&#39;bugs&#39;, &#39;bugsbunnybugs&#39;)
>>> m.next()                                   # 迭代器用next()方法返回一个匹配对象
<_sre.SRE_Match object at 0x7f5d7da71a58>      # 匹配用group()方法显示出来
>>> m.next().group()
&#39;bugs&#39;
Copy after login

使用sub()和subn()搜索与替换

都是将某字符串中所有匹配正则表达式的部分进行某种形式的替换。sub()返回一个用来替换的字符串,可以定义替换次数,默认替换所有出现的位置。subn()和sub()一样,但subn()还返回一个表示替换的总是,替换后的字符串和表示替换总数一起作为一个拥有两个元素的元组返回。

示例:

>>> r = &#39;a.b&#39;
>>> m = &#39;acb abc aab aac&#39;
>>> re.sub(r,&#39;hello&#39;,m)
&#39;hello abc hello aac&#39;
>>> re.subn(r,&#39;hello&#39;,m)
(&#39;hello abc hello aac&#39;, 2)
Copy after login

字符串也有一个replace()方法,当遇到一些模糊搜索替换的时候,就需要更为灵活的sub()方法了。

使用split()分割字符串

同样的,字符串中也有split(),但它也不能处理正则表达式匹配的分割。在re模块中,分居正则表达式的模式分隔符,split函数将字符串分割为列表,然后返回成功匹配的列表。

示例:

>>> s = &#39;1+2-3*4&#39;
>>> re.split(r&#39;[\+\-\*]&#39;,s)
[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;]
Copy after login

分组

有时在匹配的时候我们只想提取一些想要的信息或者对提取的信息作一个分类,这时就需要对正则匹配模式进行分组,只需要加上()即可。

示例:

>>> m = re.match(&#39;(\w{3})-(\d{3})&#39;,&#39;abc-123&#39;)
>>> m.group()       # 完整匹配                        
&#39;abc-123&#39;
>>> m.group(1)      # 子组1
&#39;abc&#39;
>>> m.group(2)      # 子组2
&#39;123&#39;
>>> m.groups()      # 全部子组
(&#39;abc&#39;, &#39;123&#39;)
Copy after login

由以上的例子可以看出,group()通常用于以普通方式显示所有的匹配部分,但也能用于获取各个匹配的子组。可以使用groups()方法来获取一个包含所有匹配字符串的元组。

The above is the detailed content of Detailed introduction to the re regular expression of python module. 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
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
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.

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.

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".

See all articles