Home > Backend Development > Python Tutorial > A detailed introduction to learning the re module of the Python standard library

A detailed introduction to learning the re module of the Python standard library

高洛峰
Release: 2017-03-21 09:15:06
Original
2102 people have browsed it

The re module provides a series of powerful regular expression (regular expression) tools that allow you to quickly check whether a given string matches a given pattern ( matchfunction), or contains this pattern (search function). Regular expressions are string patterns written in a compact (and mysterious) syntax.

1. Common methods

##sub(pattern, repl, string, The part of string that matches pattern, Replace with repl, up to count times subn(pattern, repl, string, count=0, flags=0) is similar to sub, returned by subn Is a replaced string and matching times##compile( pattern, flags=0)compile(pattern, flags=0)Compile a regular expression pattern into a regular purge()escape(string )Add backslashes to all characters in the string except letters and numbers

2. Special matching characters

Common methods Description
match (pattern, string, flags=0) If the beginning of the string string matches the regular expression pattern, return the corresponding instance of MatchObject, otherwise return None
search(pattern, string, flags=0) Scan string, if there is a position that matches the regular expression pattern, return an instance of MatchObject, otherwise Return None
count=0, flags=0)
arrayinto a tuple
split(pattern, string, maxsplit=0, flags=0) Use the string matched by pattern to split the string
findall(pattern, string, flags=0) Return the string matching pattern in string in the form of a list
object so that the match and search methods of the regular object can be used
Clear the regular expression cache
Syntax Description
. Matches any character except newlines
^ Header matches
$ Tail match
* Match the previous character 0 or more times
+ Match the previous character 1 or more times
? Match the previous character 0 or once
{m,n} Match the previous character m to n times
\ Escape any special character
[] is used to represent a character set combined with
| or , represents any matching of
on the left and right

3. Module method

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

Match from the beginning of the string. If pattern matches, return a Match object instance (Match object described later), otherwise None is returned. Flags is the matching mode (described below), which is used to control the matching method of regular expressions.

import re

a = &#39;abcdefg&#39;print re.match(r&#39;abc&#39;, a)  # 匹配成功print re.match(r&#39;abc&#39;, a).group()print re.match(r&#39;cde&#39;, a)  # 匹配失败>>><_sre.SRE_Match object at 0x0000000001D94578>
>>>abc
>>>None
Copy after login

search(pattern, string, flags=0)

Used to find substrings in the string that can be successfully matched. If found, a Match object instance is returned, otherwise None is returned.

import re

a = &#39;abcdefg&#39;print re.search(r&#39;bc&#39;, a)print re.search(r&#39;bc&#39;, a).group()print re.search(r&#39;123&#39;, a)

>>><_sre.SRE_Match object at 0x0000000001D94578>
>>>bc
>>>None
Copy after login

sub(pattern, repl, string, count=0, flags=0)

Replace, replace the part of string matching pattern with repl, up to count times (remaining matches will not be processed), and then the replaced string is returned.

import re

a = &#39;a1b2c3&#39;print re.sub(r&#39;\d+&#39;, &#39;0&#39;, a)  # 将数字替换成&#39;0&#39;print re.sub(r&#39;\s+&#39;, &#39;0&#39;, a)  # 将空白字符替换成&#39;0&#39;>>>a0b0c0
>>>a1b2c3
Copy after login

subn(pattern, repl, string, count=0, flags=0)

is the same as the sub() function, except that it returns a tuple containing the new string and The number of matches

import re

a = &#39;a1b2c3&#39;print re.subn(r&#39;\d+&#39;, &#39;0&#39;, a)  # 将数字替换成&#39;0&#39;>>>(&#39;a0b0c0&#39;, 3)
Copy after login

split(pattern, string, maxsplit=0, flags=0)

The regular version of split() uses the substring matching pattern to split the string. If pattern If parentheses are used, the string matched by pattern will also be used as part of the return value list, and maxsplit is the string that can be split at most.

import re

a = &#39;a1b1c&#39;print re.split(r&#39;\d&#39;, a)print re.split(r&#39;(\d)&#39;, a)

>>>[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]
>>>[&#39;a&#39;, &#39;1&#39;, &#39;b&#39;, &#39;1&#39;, &#39;c&#39;]
Copy after login

findall(pattern, string, flags=0)

Returns the non-overlapping substrings in string that match pattern in the form of a list.

import re

a = &#39;a1b2c3d4&#39;print re.findall(&#39;\d&#39;, a)

>>>[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;]
Copy after login

4. Match object

If re.match() and re.search() successfully match, they will return a Match object, which contains a lot of information about the match. You can use Match Provide properties or methods to obtain this information. For example:

>>>import re

>>>str = &#39;he has 2 books and 1 pen&#39;
>>>ob = re.search(&#39;(\d+)&#39;, str)

>>>print ob.string  # 匹配时使用的文本
he has 2 books and 1 pen

>>>print ob.re # 匹配时使用的Pattern对象
re.compile(r&#39;(\d+)&#39;)

>>>print ob.group()  # 获得一个或多个分组截获的字符串
2

>>>print ob.groups()  # 以元组形式返回全部分组截获的字符串
(&#39;2&#39;,)
Copy after login

5.Pattern object

The Pattern object object is returned by re.compile(). It has many methods of the same name in the re module, and the methods have similar functions. For example:

>>>import re
>>>pa = re.compile(&#39;(d\+)&#39;)

>>>print pa.split(&#39;he has 2 books and 1 pen&#39;)
[&#39;he has &#39;, &#39;2&#39;, &#39; books and &#39;, &#39;1&#39;, &#39; pen&#39;]

>>>print pa.findall(&#39;he has 2 books and 1 pen&#39;)
[&#39;2&#39;, &#39;1&#39;]

>>>print pa.sub(&#39;much&#39;, &#39;he has 2 books and 1 pen&#39;)
he has much books and much pen
Copy after login

6. Matching pattern

The matching pattern value can use the bitwise OR operator '|' to indicate that it takes effect at the same time, such as re.I | re. M, the following are some common flags.

  • re.I(re.IGNORECASE): Ignore case

>>>pa = re.compile(&#39;abc&#39;, re.I)
>>>pa.findall(&#39;AbCdEfG&#39;)
>>>[&#39;AbC&#39;]
Copy after login
  • re.L(re.LOCALE ): Character set localization

This function is to support multi-language version of the character set usage environment, such as escape character\w, in the English environment, it represents [a-zA-Z0-9], that is, all English characters and numbers. If used in a French environment, some French strings will not match. Add this L option and you can match. However, this seems to be of little use for the Chinese environment. It still cannot match Chinese characters.

  • re.M(re.MULTILINE): Multiline mode, change the behavior of '^' and '$'

>>>pa = re.compile(&#39;^\d+&#39;)
>>>pa.findall(&#39;123 456\n789 012\n345 678&#39;)
>>>[&#39;123&#39;]

>>>pa_m = re.compile(&#39;^\d+&#39;, re.M)
>>>pa_m.findall(&#39;123 456\n789 012\n345 678&#39;)
>>>[&#39;123&#39;, &#39;789&#39;, &#39;345&#39;]
Copy after login
  • re.S(re.DOTALL): Click any matching pattern to change the behavior of '.'

  .号将匹配所有的字符。缺省情况下.匹配除换行符\n外的所有字符,使用这一选项以后,点号就能匹配包括换行符的任何字符。

  • re.U(re.UNICODE): 根据Unicode字符集解析字符

  • re.X(re.VERBOSE): 详细模式

# 这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。以下两个正则表达式是等价的a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")# 但是在这个模式下,如果你想匹配一个空格,你必须用&#39;/ &#39;的形式(&#39;/&#39;后面跟一个空格)
Copy after login


The above is the detailed content of A detailed introduction to learning the re module of the Python standard library. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template