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.
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) | The part of string that matches pattern, Replace with repl, up to count times|
is similar to sub, returned by subn Is a replaced string and matching times | 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 |
Compile a regular expression pattern into a regular | object so that the match and search methods of the regular object can be used |
Clear the regular expression cache | |
Add backslashes to all characters in the string except letters and numbers |
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 |
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
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
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
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)
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']
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']
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',)
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
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('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 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('^\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!