Home>Article>Backend Development> 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

高洛峰
高洛峰 Original
2017-03-21 09:15:06 1980browse

The re module provides a series of powerfulregular expression(regular expression) tools that allow you to quickly check whether a givenstringmatches 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

2. Special matching characters

##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
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
objectso that the match and search methods of the regular object can be used
Clearthe regular expressioncache
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 anyspecial character
[] is used to represent acharacter setcombined 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 = 'abcdefg'print re.match(r'abc', a) # 匹配成功print re.match(r'abc', a).group()print re.match(r'cde', a) # 匹配失败>>><_sre.SRE_Match object at 0x0000000001D94578> >>>abc >>>None

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 = 'abcdefg'print re.search(r'bc', a)print re.search(r'bc', a).group()print re.search(r'123', a) >>><_sre.SRE_Match object at 0x0000000001D94578> >>>bc >>>None

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 = 'a1b2c3'print re.sub(r'\d+', '0', a) # 将数字替换成'0'print re.sub(r'\s+', '0', a) # 将空白字符替换成'0'>>>a0b0c0 >>>a1b2c3

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 = 'a1b2c3'print re.subn(r'\d+', '0', a) # 将数字替换成'0'>>>('a0b0c0', 3)

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 = 'a1b1c'print re.split(r'\d', a)print re.split(r'(\d)', a) >>>['a', 'b', 'c'] >>>['a', '1', 'b', '1', 'c']

findall(pattern, string, flags=0)

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

import re a = 'a1b2c3d4'print re.findall('\d', a) >>>['1', '2', '3', '4']

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 = 'he has 2 books and 1 pen' >>>ob = re.search('(\d+)', str) >>>print ob.string # 匹配时使用的文本 he has 2 books and 1 pen >>>print ob.re # 匹配时使用的Pattern对象 re.compile(r'(\d+)') >>>print ob.group() # 获得一个或多个分组截获的字符串 2 >>>print ob.groups() # 以元组形式返回全部分组截获的字符串 ('2',)

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('(d\+)') >>>print pa.split('he has 2 books and 1 pen') ['he has ', '2', ' books and ', '1', ' pen'] >>>print pa.findall('he has 2 books and 1 pen') ['2', '1'] >>>print pa.sub('much', 'he has 2 books and 1 pen') he has much books and much pen

6. Matching pattern

The matching pattern value can use the bitwise ORoperator'|' 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('abc', re.I) >>>pa.findall('AbCdEfG') >>>['AbC']
  • re.L(re.LOCALE ): Character set localization

This function is to support multi-language version of the character set usage environment, such asescape 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('^\d+') >>>pa.findall('123 456\n789 012\n345 678') >>>['123'] >>>pa_m = re.compile('^\d+', re.M) >>>pa_m.findall('123 456\n789 012\n345 678') >>>['123', '789', '345']
  • 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*")# 但是在这个模式下,如果你想匹配一个空格,你必须用'/ '的形式('/'后面跟一个空格)


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!

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