python中的正则表达式(regex)函数

前言

今日学习正则表达式,正则表达式是一门专门的学科,涉及到的东西很多,所以这里我只记录一些测试或者开发过程中我们经常用到的一些正则方法,我尽量概况全面一些,以简单易懂为主要目的,每个方法都会附加实例和讲解!

定义

正则表达式也叫做匹配模式(Pattern),由一组具有特定含义的字符串组成,通常用于匹配和替换文本。它是一个独立的技术,很多编程语言支持正则表达式处理。正则表达式就是一些人为定义的规则,进行组合,使其具有快速匹配字符串的功能

作用

匹配指定规则的字符串

python中使用正则

在python中使用正则表达式可以引入re模块,因为re模块是python独有的匹配字符串的模块,该模块中提供的很多功能是基于正则表达式实现的,而正则表达式是对字符串进行模糊匹配,提取自己需要的字符串部分,他对所有的语言都通用,在python中直接导入模块即可(import re)
虽然Python为外面提供了re模块供我们使用,但是功能太弱,远远无法满足我们平时的使用,所以我需要继续学习正则的其他知识
首先来看一下re模块的一些常用方法

# public interface

def match(pattern, string, flags=0):
    """Try to apply the pattern at the start of the string, returning
    a Match object, or None if no match was found."""
    return _compile(pattern, flags).match(string)

def fullmatch(pattern, string, flags=0):
    """Try to apply the pattern to all of the string, returning
    a Match object, or None if no match was found."""
    return _compile(pattern, flags).fullmatch(string)

def search(pattern, string, flags=0):
    """Scan through string looking for a match to the pattern, returning
    a Match object, or None if no match was found."""
    return _compile(pattern, flags).search(string)

def sub(pattern, repl, string, count=0, flags=0):
    """Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the Match object and must return
    a replacement string to be used."""
    return _compile(pattern, flags).sub(repl, string, count)

def subn(pattern, repl, string, count=0, flags=0):
    """Return a 2-tuple containing (new_string, number).
    new_string is the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in the source
    string by the replacement repl.  number is the number of
    substitutions that were made. repl can be either a string or a
    callable; if a string, backslash escapes in it are processed.
    If it is a callable, it's passed the Match object and must
    return a replacement string to be used."""
    return _compile(pattern, flags).subn(repl, string, count)

def split(pattern, string, maxsplit=0, flags=0):
    """Split the source string by the occurrences of the pattern,
    returning a list containing the resulting substrings.  If
    capturing parentheses are used in pattern, then the text of all
    groups in the pattern are also returned as part of the resulting
    list.  If maxsplit is nonzero, at most maxsplit splits occur,
    and the remainder of the string is returned as the final element
    of the list."""
    return _compile(pattern, flags).split(string, maxsplit)

def findall(pattern, string, flags=0):
    """Return a list of all non-overlapping matches in the string.

    If one or more capturing groups are present in the pattern, return
    a list of groups; this will be a list of tuples if the pattern
    has more than one group.

    Empty matches are included in the result."""
    return _compile(pattern, flags).findall(string)

def finditer(pattern, string, flags=0):
    """Return an iterator over all non-overlapping matches in the
    string.  For each match, the iterator returns a Match object.

    Empty matches are included in the result."""
    return _compile(pattern, flags).finditer(string)

def compile(pattern, flags=0):
    "Compile a regular expression pattern, returning a Pattern object."
    return _compile(pattern, flags)

def purge():
    "Clear the regular expression caches"
    _cache.clear()
    _compile_repl.cache_clear()

def template(pattern, flags=0):
    "Compile a template pattern, returning a Pattern object"
    return _compile(pattern, flags|T)

# SPECIAL_CHARS
# closing ')', '}' and ']'
# '-' (a range in character set)
# '&', '~', (extended character set operations)
# '#' (comment) and WHITESPACE (ignored) in verbose mode
_special_chars_map = {i: '\\' + chr(i) for i in b'()[]{}?*+-|^$\\.&~# \t\n\r\v\f'}

def escape(pattern):
    """
    Escape special characters in a string.
    """
    if isinstance(pattern, str):
        return pattern.translate(_special_chars_map)
    else:
        pattern = str(pattern, 'latin1')
        return pattern.translate(_special_chars_map).encode('latin1')

Pattern = type(sre_compile.compile('', 0))
Match = type(sre_compile.compile('', 0).match(''))

match:指定匹配

match函数是个匹配函数,作用就是根据指定的规则匹配字符串
match函数会从字符串的开头位置进行匹配,同时设置一个标志位(开始,结束,开始结束)如果不是起始位置匹配成功的话,match()就返回none。
语法及参数:
match(pattern, string, flags=0)
pattern:匹配规则模式
string:要匹配的字符串
flags:标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等
可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。
匹配对象方法描述:
group(num=0)
匹配的整个表达式的字符串,group() 可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。
groups()返回一个包含所有小组字符串的元组,从 1 到 所含的小组号

import re
# re.match 返回一个Match Object 对象
# 对象提供了 group() 方法,来获取匹配的结果
result = re.match("hello","hello,world")
if result:
print(result.group())
else:
print("匹配失败!")

输出结果:
hello

group的用法:

import re
line = "Cats are smarter than dogs"
# .* 表示任意匹配除换行符(\)之外的任何单个或多个字符
matchObj = re.match( r"(.*) are (.*?) .*", line, re.M|re.I)
if matchObj:
print ("matchObj.group() : ", matchObj.group())
print ("matchObj.group(1) : ", matchObj.group(1))
print ("matchObj.group(2) : ", matchObj.group(2))
else:
print ("No match!!")

以上实例执行结果如下:
matchObj.group() :  Cats are smarter than dogs
matchObj.group(1) :  Cats
matchObj.group(2) :  smarter

在这里插入图片描述

fullmatch:精准匹配

完全匹配(从字符串开头到结尾),可以理解成匹配pattern是否与整个string匹配,完全一样的字符串才可以匹配到,否则返回None
与match的用法类似
语法:fullmatch(pattern, string, flags=0)
match:字符串开头的零个或多个字符与该正则表达式匹配
一开始就锚定了 ^pattern,确保字符串以模式开头
fullmatch:整个字符串与此正则表达式匹配
锚定在图案的开头和结尾 ^pattern , 确 保 完 整 的 字 符 串 与 模 式 匹 配 ( 对 于 此 处 所 述 的 交 替 操 作 尤 其 有 用 ) 使 用 和 ,确保完整的字符串与模式匹配(对于此处所述的交替操作尤其有用) 使用^和 使来限定匹配字符串的开始和结束
在这里插入图片描述

# -*- coding:UTF8 -*-
import re

qq = '18267532342'
#x*  匹配0个或者任意多个x(.* 表示匹配0个或者任意多个字符(换行符除外))(贪婪匹配【尽可能多的匹配】)
#x{n,m}   匹配至少n个最多m个x。注意:n <= m
#[0-9]  匹配任意数字,类似[0123456789]
#\d   匹配数字,效果同[0-9]
result = re.fullmatch(r'[1-9]\d{4,11}', qq)#
print(result)#<re.Match object; span=(0, 10), match='1826755263'>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

search:扫描匹配

扫描整个字符串并返回第一个成功的匹配,如果匹配失败,则返回None
search()并不要求必须从字符串的开头进行匹配,也就是说,正则表达式可以是字符串的一部分
语法:re.search(pattern, string, flags=0)

# -*- coding:UTF8 -*-
 
import re

content = 'Hello 123456 Word_This is only a test data'
result = re.search('(\d+).*?(\d+).*', content)  
 
print(result)
print(result.group())    # print(result.group(0)) 同样效果字符串
print(result.groups())
print(result.group(1))

在这里插入图片描述
只匹配数字:
在这里插入图片描述
match和search的区别:
match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而search匹配整个字符串,直到找到一个匹配。

sub:替换

将正则表达式 pattern 匹配到的全部字符串替换为 repl 指定的字符串,
参数 count 用于指定最大替换次数
语法:re.sub(pattern, repl, string, count=0, flags=0)
re.sub共有五个参数:
三个必选参数:pattern, repl, string
两个可选参数:count, flags
pattern:正则中的模式字符串
repl:替换的字符串,也可以是一个函数
如果repl是字符串的话,其中的任何反斜杠转义字符,都会被处理的。
即:
1)\n:会被处理为对应的换行符;
2)\r:会被处理为回车符;
3)其他不能识别的转移字符,则只是被识别为普通的字符:
比如\j,会被处理为j这个字母本身;
4)反斜杠加g以及中括号内一个名字,即:\g,对应着命了名的组,named group
string:要被查找替换的原始字符串
count:模式匹配后替换的最大次数,默认 0 表示替换所有的匹配
flags:编译时用的匹配模式(如忽略大小写、多行模式等),数字形式,默认为0

# -*- coding:UTF8 -*-
 
import re

content = 'Hello 123456 Word_This is only a test data'
result = re.sub('[0-9]','*',content)   
print(result)#Hello ****** Word_This is only a test data

在这里插入图片描述
re.sub(r’[0-9]+’, ‘*’, s) 表示匹配多个连续的数字,并将多个连续的数字替换为一个星号

# -*- coding:UTF8 -*- 
import re

content = 'Hello 123456 Word_This is 333111 a test data'
result = re.sub('[0-9]+','*',content)  
print(result)#Hello * Word_This is * a test data

在这里插入图片描述
sub(r’[0-9]+’, ‘’, s) 这句话则表示匹配多个连续的数字,并将多个连续的数字替换为一个星号
re.sub(r’[0-9A-Za-z]+’, '
’, s) 这句话则表示匹配多个连续的数字和字母,并将多个连续的数字、连续的字母、连续的数字和字母替换为一个星号
re.sub(r’[^0-9]’, ‘*’, s) 这句话则表示匹配非数字,替换为一个星号
repl是函数时:
将字符串中的匹配的数字乘以 2

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
import re
 
# 将匹配的数字乘以 2
def double(matched):
    value = int(matched.group('value'))
    return str(value * 2)
 
s = 'A23G4HFD567'
print(re.sub('(?P<value>\d+)', double, s))#A46G8HFD1134

在这里插入图片描述

subn:同sub

用法和意义同sub(后续补充!)

split:分割

split能够按照所能匹配的字串将字符串进行切分,返回切分后的字符串列表
对于一个找不到匹配的字符串而言,split 不会对其作出分割
语法:re.split(pattern, string[, maxsplit=0, flags=0])
参数:
pattern:匹配的字符串
string:需要切分的字符串
maxsplit:分隔次数,默认为0(即不限次数)
flags:标志位,用于控制正则表达式的匹配方式,比如:是否区分大小写,,,如下图所示
\W+:匹配非数字,字母和下划线,进行切割
如果加上括号,结果会同时返回去掉的值

# -*- coding:UTF8 -*-
 
import re
content = 'Hello 123456 Word_This is 333111 a test data'
result = re.split('\W',content)   
print(result)
#['Hello', '123456', 'Word_This', 'is', '333111', 'a', 'test', 'data']

在这里插入图片描述

# -*- coding:UTF8 -*-
 
import re

content = 'Word_This, is ,333111'
result = re.split('(\W+)',content)  
#['Word_This', ', ', 'is', ' ,', '333111'] 
print(result)

在这里插入图片描述
在这里插入图片描述
只分割一次:

# -*- coding:UTF8 -*-
 
import re

content = 'Word_This, is ,333111'
result = re.split('(\W+)',content,1)  
#['Word_This', ', ', 'is ,333111'] 
print(result)

在这里插入图片描述
找不到的字符串,不进行切割:

# -*- coding:UTF8 -*-
 
import re

content = 'Word_This, is ,333111'
result = re.split('(\W+)','qqq')  
 
print(result)
#['qqq']

在这里插入图片描述

findall:匹配文本字符串的字面值

在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表
需要注意的是:findall是匹配所有
语法格式:re.findall(pattern,string,flags=0)
第一个参数:pattern 正则表达式的规则 目标字符串
(如果pattern里没有组,或只有一个组,返回列表,元素是匹配到的字符串)
第二个参数:string 要检测的字符串,看是否有符合pattern正则表达式的部分,如果有就返回,没有即返回None
第三个参数:flags 匹配标记,默认为0

# -*- coding:UTF8 -*-
 
import re
 
pattern = re.compile(r'\d+')   # 查找数字
result1 = pattern.findall('runoob 123 google 456')
result2 = pattern.findall('run88oob123google456', 0, 10)#查找前十个字符串内的数字
#打印结果
print(result1)#['123', '456']
print(result2)#['88', '12']

finditer:匹配字符串

跟findall方法类似的还有finditer,不过这个方法返回的是一个迭代器,而findall返回的是一个列表

# -*- coding:UTF8 -*-
 
import re
 
pattern = re.compile(r'\d+')   # 查找数字
result1 = pattern.findall('runoob 123 google 456')
result2 = pattern.finditer('run88oob123google456', 0, 10)#查找前十个字符串内的数字
#打印结果
print(result1)#['123', '456']
print(result2)#<callable_iterator object at 0x00000000006A4FA0>

在这里插入图片描述

compile:编译正则表达式

用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用
re.compile()生成的是正则对象,单独使用没有任何意义,需要和findall(), search(), match()搭配使用
compile函数根据包含的正则表达式的字符串创建模式对象。可以实现更有效率的匹配。在直接使用字符串表示的正则表达式进行search,match和findall操作时,python会将字符串转换为正则表达式对象。而使用compile完成一次转换之后,在每次使用模式的时候就不用重复转换
步骤:
1)使用 compile 函数将正则表达式的字符串形式编译为一个 Pattern 对象
2)通过 Pattern 对象提供的一系列方法对文本进行匹配查找,获得匹配结果(一个 Match 对象)
3)最后使用 Match 对象提供的属性和方法获得信息,根据需要进行其他的操作
语法:re.compile(pattern[, flags])
参数:
pattern : 一个字符串形式的正则表达式
flags : 可选,表示匹配模式,比如忽略大小写,多行模式等,具体参数为:
re.I 忽略大小写
re.L 表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境
re.M 多行模式
re.S 即为 . 并且包括换行符在内的任意字符(. 不包括换行符)
re.U 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库
re.X 为了增加可读性,忽略空格和 # 后面的注释

结合findall使用:
匹配含有字母“e”的单词

# -*- coding:UTF8 -*-
import re

content = 'Hello, this is a test data, 123456'
reg = re.compile('\w*e\w*')
x = reg.findall(content)
print(x)  # ['Hello', 'test']

在这里插入图片描述
结合search使用:
匹配含有“e”的第一个单词

# -*- coding:UTF8 -*-
import re

content = 'Hell, this is a test data, 123456'
regex = re.compile('\w*e\w*')
z = regex.search(content)
print(z) #<re.Match object; span=(0, 4), match='Hell'>
print(z.group()) #Hell
print(z.span()) #(0, 4)

在这里插入图片描述
结合match使用:

# -*- coding:UTF8 -*-
import re
pattern = re.compile(r'([a-z]+) ([a-z]+)', re.I) # re.I 表示忽略大小写
m = pattern.match('Hello World Wide Web')
# 匹配成功,返回一个 Match 对象
print(m) #<_sre.SRE_Match object at 0x10bea83e8>
# 返回匹配成功的整个子串
print(m.group(0)) #'Hello World'
# 返回匹配成功的整个子串的索引
print(m.span(0)) #(0, 11)
# 返回第一个分组匹配成功的子串
print(m.group(1)) #'Hello'
# 返回第一个分组匹配成功的子串的索引
print(m.span(1)) #(0, 5)
# 返回第二个分组匹配成功的子串
print(m.group(2)) #'World'
# 返回第二个分组匹配成功的子串
print(m.span(2)) #(6, 11)
# 等价于 (m.group(1), m.group(2), ...)
print(m.groups()) #('Hello', 'World')

在这里插入图片描述

purge:清除隐式编译的正则表达式的缓存

源码写的是清除正则表达式的缓存,目前还不太清楚清楚的是哪里的缓存,有待研究!!!

template:不太清楚干啥的。。。

escape:去除转义字符

re.escape(pattern) 可以对文本(字符串)中所有可能被解释为正则运算符的字符进行转义的应用函数
re.escape(pattern) 可以对字符串中所有可能被解释为正则运算符的字符进行转义的应用函数。如果字符串很长且包含很多特殊技字符,而你又不想输入一大堆反斜杠,或者字符串来自于用户(比如通过raw_input函数获取输入的内容),且要用作正则表达式的一部分的时候,可以使用这个函数
语法:re.escape(pattern)

# -*- coding:UTF8 -*-
import re
pattern = re.escape(r'www.baidu.com')
print(pattern)
#www\.baidu\.com

在这里插入图片描述

re底层:正则表达式元字符

The special characters are:
    "."      Matches any character except a newline.
    "^"      Matches the start of the string.
    "$"      Matches the end of the string or just before the newline at
             the end of the string.
    "*"      Matches 0 or more (greedy) repetitions of the preceding RE.
             Greedy means that it will match as many repetitions as possible.
    "+"      Matches 1 or more (greedy) repetitions of the preceding RE.
    "?"      Matches 0 or 1 (greedy) of the preceding RE.
    *?,+?,?? Non-greedy versions of the previous three special characters.
    {m,n}    Matches from m to n repetitions of the preceding RE.
    {m,n}?   Non-greedy version of the above.
    "\\"     Either escapes special characters or signals a special sequence.
    []       Indicates a set of characters.
             A "^" as the first character indicates a complementing set.
    "|"      A|B, creates an RE that will match either A or B.
    (...)    Matches the RE inside the parentheses.
             The contents can be retrieved or matched later in the string.
    (?aiLmsux) The letters set the corresponding flags defined below.
    (?:...)  Non-grouping version of regular parentheses.
    (?P<name>...) The substring matched by the group is accessible by name.
    (?P=name)     Matches the text matched earlier by the group named name.
    (?#...)  A comment; ignored.
    (?=...)  Matches if ... matches next, but doesn't consume the string.
    (?!...)  Matches if ... doesn't match next.
    (?<=...) Matches if preceded by ... (must be fixed length).
    (?<!...) Matches if not preceded by ... (must be fixed length).
    (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
                       the (optional) no pattern otherwise.

The special sequences consist of "\\" and a character from the list
below.  If the ordinary character is not on the list, then the
resulting RE will match the second character.
    \number  Matches the contents of the group of the same number.
    \A       Matches only at the start of the string.
    \Z       Matches only at the end of the string.
    \b       Matches the empty string, but only at the start or end of a word.
    \B       Matches the empty string, but not at the start or end of a word.
    \d       Matches any decimal digit; equivalent to the set [0-9] in
             bytes patterns or string patterns with the ASCII flag.
             In string patterns without the ASCII flag, it will match the whole
             range of Unicode digits.
    \D       Matches any non-digit character; equivalent to [^\d].
    \s       Matches any whitespace character; equivalent to [ \t\n\r\f\v] in
             bytes patterns or string patterns with the ASCII flag.
             In string patterns without the ASCII flag, it will match the whole
             range of Unicode whitespace characters.
    \S       Matches any non-whitespace character; equivalent to [^\s].
    \w       Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]
             in bytes patterns or string patterns with the ASCII flag.
             In string patterns without the ASCII flag, it will match the
             range of Unicode alphanumeric characters (letters plus digits
             plus underscore).
             With LOCALE, it will match the set [0-9_] plus characters defined
             as letters for the current locale.
    \W       Matches the complement of \w.
    \\       Matches a literal backslash.

This module exports the following functions:
    match     Match a regular expression pattern to the beginning of a string.
    fullmatch Match a regular expression pattern to all of a string.
    search    Search a string for the presence of a pattern.
    sub       Substitute occurrences of a pattern found in a string.
    subn      Same as sub, but also return the number of substitutions made.
    split     Split a string by the occurrences of a pattern.
    findall   Find all occurrences of a pattern in a string.
    finditer  Return an iterator yielding a Match object for each match.
    compile   Compile a pattern into a Pattern object.
    purge     Clear the regular expression cache.
    escape    Backslash all non-alphanumerics in a string.

Each function other than purge and escape can take an optional 'flags' argument
consisting of one or more of the following module constants, joined by "|".
A, L, and U are mutually exclusive.
    A  ASCII       For string patterns, make \w, \W, \b, \B, \d, \D
                   match the corresponding ASCII character categories
                   (rather than the whole Unicode categories, which is the
                   default).
                   For bytes patterns, this flag is the only available
                   behaviour and needn't be specified.
    I  IGNORECASE  Perform case-insensitive matching.
    L  LOCALE      Make \w, \W, \b, \B, dependent on the current locale.
    M  MULTILINE   "^" matches the beginning of lines (after a newline)
                   as well as the string.
                   "$" matches the end of lines (before a newline) as well
                   as the end of the string.
    S  DOTALL      "." matches any character at all, including the newline.
    X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.
    U  UNICODE     For compatibility only. Ignored for string patterns (it
                   is the default), and forbidden for bytes patterns.

This module also defines an exception 'error'.

正则表达式的元字符

匹配单个字符和数字

.                匹配除换行符以外的任意字符
[0123456789]     []是字符集合,表示匹配方括号中所包含的任意一个字符
[good]           匹配good中任意一个字符
[a-z]            匹配任意小写字母
[A-Z]            匹配任意大写字母
[0-9]            匹配任意数字,类似[0123456789]
[0-9a-zA-Z]      匹配任意的数字和字母
[0-9a-zA-Z_]     匹配任意的数字、字母和下划线
[^good]          匹配除了good这几个字母以外的所有字符,中括号里的^称为脱字符,表示不匹配集合中的字符
[^0-9]           匹配所有的非数字字符
\d               匹配数字,效果同[0-9]
\D               匹配非数字字符,效果同[^0-9]
\w               匹配数字,字母和下划线,效果同[0-9a-zA-Z_]
\W               匹配非数字,字母和下划线,效果同[^0-9a-zA-Z_]
\s               匹配任意的空白符(空格,回车,换行,制表,换页),效果同[ \r\n\t\f]
\S               匹配任意的非空白符,效果同[^ \f\n\r\t]

锚字符(边界字符)

^     行首匹配,和在[]里的^不是一个意思,"^"要写到字符串的前面,在默认模式下匹配字符串的起始位置
$     行尾匹配,"$"要写到匹配的字符串后面,匹配字符串的末尾或者字符串末尾换行符之前的位置
*	  匹配前面重复出现的正则表达式零次或多次,尽可能多的匹配。ab*将匹配'a''ab''a'后面跟随任意数目的'b'+	  引起生成的RE匹配1个或多个前导的RE,尽可能多的匹配。ab+将匹配'a'之后跟随任意多个数目不为零的'b',它将不能匹配单纯的一个'a'。
?	  引起生成的RE匹配0个或1个前导的RE。ab?将匹配'a'或者'ab'。
\A    匹配字符串的开始,它和^的区别是,\A只匹配整个字符串的开头,即使在re.M模式下也不会匹配其它行的行首
\Z    匹配字符串的结束,它和$的区别是,\Z只匹配整个字符串的结束,即使在re.M模式下也不会匹配它行的行尾

\b    匹配一个单词的边界,也就是值单词和空格间的位置
      'er\b'可以匹配never,不能匹配nerve
\B    匹配非单词边界

匹配多个字符

说明:下方的x、y、z均为假设的普通字符,n、m(非负整数),不是正则表达式的元字符
(xyz)    匹配小括号内的xyz(作为一个整体去匹配)
x?       匹配0个或者1个x(非贪婪匹配【尽可能少的匹配】)
x*       匹配0个或者任意多个x(.* 表示匹配0个或者任意多个字符(换行符除外)(贪婪匹配【尽可能多的匹配】)
x+       匹配至少一个x(贪婪匹配)
x{n}     匹配确定的n个x(n是一个非负整数),例如,a{6}将精确匹配6'a'字符,5个将不能匹配。
x{n,}    匹配至少n个x
x{n,m}   匹配至少n个最多m个x。注意:n <= m(例如,a{3,5}将匹配35'a'字符。省略m表示下界为0,省略n表示上界无限大)
x|y      |表示或,匹配的是x或y
{m,n}?	 例如,对于6个字符的字符串'aaaaaa',a{3,5}将匹配5'a'字符,而a{3,5}?将只匹配3个字符。

特殊字符

*?   +?   x?  最小匹配,通常都是尽可能多的匹配,可以使用这种解决贪婪匹配(?:x)    类似(xyz),但不表示一个组
*? ,  +? ,  ??
'*''+''?'限定符是贪婪的; 它们匹配尽可能多的文本。有时这个行为不是想要的;如果用正则表达式 <.*>来匹配 '<H1>title</H1>',它将匹配完整的字符串,而不会只是 '<H1>'。在限定符之后加上 '?'将使得匹配以非贪婪的或最小的方式进行;因为它将匹配尽可能少的字符。在刚才的表达式中使用 .*?将只匹配 '<H1>'
\	  对任一特殊字符进行转义(允许您匹配字符(如'*'' ? ',等等),或只是一个特殊的序列;特殊序列在下面讨论。
如果不使用原始字符串来表达模式,记住在字符串字面值中Python也使用反斜杠作为转义序列;如果转义序列不能被Python解析器识别,那么结果字符串中包含反斜杠和后面的字符。但是,如果Python会识别所产生的序列,反斜杠应该重复两次。这比较复杂和难以理解,因此强烈建议你为所有即使是最简单的表达式使用原始字符串
[]
表示一组字符。
作为第一个字符的“^”表示补集。
 "|"      
A|B ,此处的A和B可以是任意的正则表达式,创建的这个正则表达式要么匹配A要么匹配B.  '|'可以用来隔开任意个数的正则表达式,着同样可以用在组里面。 当扫描字符串时,REs被用 '|'从左到右分隔。当一个模式被完全匹配时,这个被匹配的模式就被接受。这意味着一旦匹配 A  ,  B  就不在被尝试,即使他会产生更长的整体匹配. 换句话说,   '|'  不是贪婪操作符. 匹配符号  '|' ,| ,或者把它包含在组内,就像是  [|] .
 (...)    
匹配任何在圆括号内的正则表达式,并表明分组的开始和结束;  分组的内容在完成匹配后可以提取出来,而且可以在后面的字符串中用特殊的number序列匹配,下面有描述。若要匹配字面值'('')',请使用(  or  ),或它们放入字符类的括号中:[(]  [)](?aiLmsux) 
这些字母设置了下面定义的相应标志。
(?:...)
括号形式的正则表达式的非匹配版本。匹配括号中的任何正则表达式,但是匹配的子字符串不能在匹配后提取或在模式中引用。
(?P<name>...)
通过符号组名称name可以访问类似于常规的括号,但由组匹配的子字符串。组名必须是有效的Python标识符,并且每个组名必须在正则表达式内只有一次定义。海员象征性的组织也是带编号的组,就好像组未被命名

(?P=name)
对命名组的反向引用;反向关联一个已被命名的字符串组。 它将匹配之前被关联到name中的所有内容。
(?#...)
一条注释;圆括号内容可简单忽略。
(?=...)
如果匹配。。。匹配下一个,但不使用任何字符串。这称为前瞻断言。例如,Isaac(?=Asimov)只有在后跟“Asimov”时才会匹配“Isaac”。
(?!...)
如果匹配。。。与下一个不匹配。这是一个消极的前瞻性断言。例如, Isaac(?)?!Asimov)只有在后面没有“Asimov”时才会与“Isaac”匹配。
(?<=...)
如果在字符串中的当前位置之前由...匹配项的比赛,在当前的位置结束。这就被所谓的积极回顾后发断言。(? < = abc) def将发现一个匹配abcdef,因为预测先行将备份3个字符,并检查是否包含的模式匹配。包含的模式必须只匹配固定长度的字符串,这意味着允许abc  或a|b  的,但a*  和a{3,4}  不允许。请注意,开始与正预测先行断言的模式将不匹配开头的字符串被搜查;您将最有可能想要使用search ()函数,而不是match ()函数

(?<!...)
如果字符串的当前位置不匹配之前的  ... .  这叫做  否定性回顾断言
  • 8
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十七光年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值