Home  >  Article  >  Backend Development  >  Detailed introduction to the re regular expression of python module

Detailed introduction to the re regular expression of python module

高洛峰
高洛峰Original
2017-03-15 15:18:481921browse

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模块中的大多数函数和已经编译的正则表达式对象和正则匹配对象的方法同名并且具有相同的功能

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 用来使正则匹配模式组织得更加清晰

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> # 确认返回的匹配对象

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;

 使用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;

 使用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)

字符串也有一个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;]

分组

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

示例:

>>> 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;)

由以上的例子可以看出,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:
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