资讯专栏INFORMATION COLUMN

python模块之re(正则表达式)

Cheriselalala / 884人阅读

摘要:多行模式,改变元字符和的行为。模块级方法编译正则表达式,返回一个对象。扫描参数,查找正则表达式产生匹配的第一个结果,返回一个对象。清空正则表达式缓存。和参数意义同与模块级的相同与模块级的相同属性返回一个正整数,表示正则匹配模式。

匹配模式

re.ASCII
re.A,对应的内联标识为(?a),用于向后兼容。使元字符w, W, , B, d, D, sS仅匹配ASCII字符。该模式只在string模式下有意义,在byte模式下将被忽略。

re.DEBUG
显示debug信息,没有对应的内联标识。

re.IGNORECASE
re.I,对应的内联标识是(?i)。忽略大小写匹配,如表达式[A-Z]也会匹配小写的字母a-z。对Unicode字符同样生效(如"Ü"可以匹配"ü"),除非指定了re.ASCII禁止匹配非ASCII字符。

当前locale不会改变此标识的效果,除非指定了re.LOCALE

在string模式下[a-z],[A-Z]和IGNORECASE标识结合使用时,将匹配52个ASCII字母和4个非ASCII字母。

re.LOCALE
re.L,对应的内联标识为(?L)。不推荐使用。

re.MULTILINE
re.M,对应的内联标识为(?m)。多行模式,改变元字符^$的行为。
默认^只匹配字符串开始,指定后还会匹配每行的开始(换行符之后);默认$只匹配字符串结尾,指定后还会匹配每行结尾(换行符之前)。

re.DOTALL
re.S,对应的内联标识为(?s)。此模式下,元字符.匹配任意字符,包括换行符。

re.VERBOSE
re.X,对应的内联标识为(?x)。冗余模式,此模式下可以在表达式中添加注释,使其更具可读性,但在编译时会忽略多余的空格和注释。

模块级方法 re.compile(pattern, flags=0)

编译正则表达式pattern,返回一个SRE_Pattern对象。flags参数指定匹配模式。

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

扫描string参数,查找正则表达式pattern产生匹配的第一个结果,返回一个SRE_Match对象。如果返回None表示匹配失败

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

如果string参数开头的0个或多个字符匹配正则表达式pattern,返回一个SRE_Match对象。如果返回None表示匹配失败

即使在MULTILINE模式下,match()函数也只会匹配字符串开头,而不会匹配每行开头

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

如果string参数整个匹配正则表达式pattern,返回一个SRE_Match对象。如果返回None表示匹配失败。

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

正则表达式pattern作为分隔符拆分string参数,返回拆分后的列表。maxsplit如果不为0,最多拆分maxsplit次,string参数的余下部分将作为列表的最后一个元素返回。如果在pattern中使用了分组(...),返回列表中还会包含所有匹配的分组本身。

>>> re.split(r"W+", "Words, words, words.")
["Words", "words", "words", ""]

>>> re.split(r"(W+)", "Words, words, words.")
["Words", ", ", "words", ", ", "words", ".", ""]

>>> re.split(r"W+", "Words, words, words.", 1)
["Words", "words, words."]

>>> re.split("[a-f]+", "0a3B9", flags=re.IGNORECASE)
["0", "3", "9"]

如果pattern在字符串的开头匹配,那么返回列表第一个元素是空字符串;同样地,如果pattern在字符串末尾匹配,返回列表的最后一个元素是空字符串:

>>> re.split(r"(W+)", "...words, words...")
["", "...", "words", ", ", "words", "...", ""]
re.findall(pattern, string, flags=0)

返回一个列表,按顺序排列所有成功的分组匹配。如果pattern参数中只有一个分组,列表元素为所有成功的分组匹配;如果存在超过一个以上的分组,列表元素为元组形式的各个分组匹配。如果返回空列表表示匹配失败

>>> content = "333STR1666STR299"

>>> regex = r"([A-Z]+(d))"
>>> re.findall(regex, content)
[("STR1", "1"), ("STR2", "2")]

>>> regex1 = r"[A-Z]+(d)"
>>> re.findall(regex1, content)
["1", "2"]

# 如果正则表达式不含分组,视其整体为一个分组
>>> regex2 = r"[A-Z]+d"
>>> re.findall(regex2, content)
["STR1", "STR2"]

>>> regex3 = r"([A-Z]+d)"
>>> re.findall(regex3, content)
["STR1", "STR2"]
re.finditer(pattern, string, flags=0)

查找所有匹配成功的字符串, 返回一个迭代器,元素为SRE_Match对象。如果返回空迭代器表示匹配失败

content = "333STR1666STR299"
regex = r"([A-Z]+(d))"
result = re.finditer(regex, content)
for i in result:
    print(i.group(0))

# STR1
# STR2
re.sub(pattern, repl, string, count=0, flags=0)

使用pattern匹配原始字符串string,将匹配到的结果用repl替换,返回一个新的字符串。如果没有匹配返回原字符串。

count是一个正整数,表示字符串替换的最大次数。

repl可以是字符串或函数,如果是字符串,其中的的所有都将进行转义处理,比如 表示换行符,反向引用6表示pattern匹配的第六个分组,而某些无意义的转义可能原样保留或导致异常:

>>> re.sub(r"defs+([a-zA-Z_][a-zA-Z_0-9]*)s*(s*):",
...        r"static PyObject*
py_1(void)
{",
...        "def myfunc():")
"static PyObject*
py_myfunc(void)
{"

如果repl是函数,该函数接收单个SRE_Match对象为参数,pattern匹配到一次结果便会调用一次该函数,返回要替换的字符串:

>>> def dashrepl(matchobj):
...     if matchobj.group(0) == "-": return " "
...     else: return "-"
>>> re.sub("-{1,2}", dashrepl, "pro----gram-files")
"pro--gram files"
>>> re.sub(r"sANDs", " & ", "Baked Beans And Spam", flags=re.IGNORECASE)
"Baked Beans & Spam"
re.subn(pattern, repl, string, count=0, flags=0)

同sub(),但返回值为(new_string, number_of_subs_made)

re.escape(pattern)

转义特殊字符。

re.purge()

清空正则表达式缓存。

异常

exception re.error(msg, pattern=None, pos=None)

属性

msg:未格式化的错误信息

pattern:正则表达式

pos:导致异常的pattern索引位置,可能为None

lineno:pos在第几行,可能为None

colno:pos在所在行的位置,可能为None

Pattern对象
方法

Pattern.search(string[, pos[, endpos]])

与模块级的search()类似。pos和endpos表示string参数的前endpos个字符中,从索引为pos的位置开始匹配,如果endpos小于等于pos,返回None

Pattern.match(string[, pos[, endpos]])

与模块级的match()类似。pos和endpos参数意义同search()

>>> pattern = re.compile("o")
>>> pattern.match("dog")      # No match as "o" is not at the start of "dog".
>>> pattern.match("dog", 1)   # Match as "o" is the 2nd character of "dog".

Pattern.fullmatch(string[, pos[, endpos]])

与模块级的fullmatch()类似。pos和endpos参数意义同search()

>>> pattern = re.compile("o[gh]")
>>> pattern.fullmatch("dog")      # No match as "o" is not at the start of "dog".
>>> pattern.fullmatch("ogre")     # No match as not the full string matches.
>>> pattern.fullmatch("doggie", 1, 3)   # Matches within given limits.

Pattern.split(string, maxsplit=0)

与模块级的split()相同

Pattern.findall(string[, pos[, endpos]])

与模块级的findall()类似。pos和endpos参数意义同search()

Pattern.finditer(string[, pos[, endpos]])

与模块级的finditer()类似。pos和endpos参数意义同search()

Pattern.sub(repl, string, count=0)

与模块级的sub()相同

Pattern.subn(repl, string, count=0)

与模块级的subn()相同

属性

Pattern.flags:返回一个正整数,表示正则匹配模式。该值是compile()函数中pattern参数中的内联标识以及flags参数指定的模式,和隐式的re.UNICODE(如果pattern为Unicode字符串)的值的和

>>> re.UNICODE


>>> re.IGNORECASE


# 32 + 2
>>> re.compile("", flags=re.IGNORECASE).flags
34

Pattern.groups:pattern中存在的分组数量

Pattern.groupindex:正则表达式中所有命名分组名称和对应分组号的映射;如果没有使用命名分组,返回一个空字典

>>> pattern = re.compile(r"(?Pw+) (?Pw+)")
>>> pattern.groupindex
mappingproxy({"first_name": 1, "last_name": 2})

Pattern.pattern:编译pattern对象的正则表达式

Match对象
方法
Match.expand(template)

通过对template中的反斜杠引用进行替换,返回替换后的字符串。例如 将转义为换行符,1, g将替换为Match对象中对应的分组:

>>> m = re.search("(b)+(z)?", "cba")
>>> m

>>> m.expand(r"ab1")
"abb"
>>> m.expand(r"ab2")
"ab"
>>> print(m.expand(r"ab
"))
ab

>>>
Match.group([group1, ...])

返回Match对象的一个或多个子分组。如果传入单个参数,返回单个字符串;如果传入多个参数,返回一个元组,元组中的每个元素代表每个参数对应的分组。

如果参数为0,返回值为pattern匹配的完整字符串

如果参数在1-99范围内,返回对应分组匹配的字符串

如果参数为负数或大于pattern中定义的分组数量,抛出IndexError异常

如果对应分组无匹配,返回None

如果一个分组匹配多次,只返回最后一次匹配的结果

>>> m = re.match(r"(w+) (w+)(d+)?", "Isaac Newton, physicist")

>>> m.group(0)       # (1)
"Isaac Newton

>>> m.group(1)       # (2)
"Isaac"
>>> m.group(2)       # (2)
"Newton"
>>> m.group(1, 2)    # Multiple arguments give us a tuple.
("Isaac", "Newton")

>>> type(m.group(3)) # (4)


>>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
>>> m.group(1)                        # (5)
"c3"

如果正则表达式中使用了(?P...),group()也支持通过分组名的方式访问分组,分组名不存在将抛出IndexError异常:

>>> m = re.match(r"(?Pw+) (?Pw+)", "Malcolm Reynolds")
>>> m.group("first_name")
"Malcolm"
>>> m.group("last_name")
"Reynolds"

# 仍然可以通过索引访问
>>> m.group(1)
"Malcolm"
>>> m.group(2)
"Reynolds"
Match.__getitem__(g)

等同于group(),提供了更简单的访问分组的方式:

>>> m = re.match(r"(w+) (w+)", "Isaac Newton, physicist")
>>> m[0]       # The entire match
"Isaac Newton"
>>> m[1]       # The first parenthesized subgroup.
"Isaac"
>>> m[2]       # The second parenthesized subgroup.
"Newton"

>>> m = re.match(r"(?Pw+) (?Pw+)", "Malcolm Reynolds")
>>> m["first_name"]
"Malcolm"
Match.groups(default=None)

返回一个包含所有子分组的元组,元组长度等同于pattern中的分组数量;如果没有分组,返回空元组。default参数作为分组无匹配值时的默认值,默认为None:

>>> m = re.match(r"(d+).(d+)", "24.1632")
>>> m.groups()
("24", "1632")

>>> m = re.match(r"(d+).?(d+)?", "24")
>>> m.groups()      # Second group defaults to None.
("24", None)
>>> m.groups("0")   # Now, the second group defaults to "0".
("24", "0")
Match.groupdict(default=None)

返回一个字典,key为pattern中定义的分组名称,value为分组的匹配值;如果没有使用命名元组,返回空字典。default参数作为分组无匹配值时的默认值,默认为None:

>>> m = re.match(r"(?Pw+) (?Pw+)", "Malcolm Reynolds")
>>> m.groupdict()
{"first_name": "Malcolm", "last_name": "Reynolds"}
Match.start([group]) Match.end([group])

返回由group匹配的子字符串在原始字符串中的开始和结束索引。

group默认为0,表示完整匹配结果。

如果返回-1,表示group存在但没有匹配值

如果m.start(group)等同于m.end(group),表示group匹配一个空字符串

>>> m = re.match(r"(w+) (w+)(d)?", "Isaac Newton, physicist")
>>> m


# (1)
>>> m.start()
0
>>> m.end()
12

# (2)
>>> type(m[3])

>>> m.start(3)
-1
>>> m.end(3)
-1

# (3)
>>> m[3]
""
>>> m.start(3)
12
>>> m.end(3)
12
Match.span([group])

返回(m.start(group), m.end(group))形式的元组,如果group不存在对应匹配值,返回(-1, -1)。group默认为0,表示完整匹配结果

属性

Match.pos:传递给Pattern对象的search(), match(), fullmatch()方法的pos参数

Match.endpos:传递给Pattern对象的search(), match(), fullmatch()方法的endpos参数

Match.lastindex:具有匹配值的最后一个分组的位置,如果没有任何分组匹配,返回None。

>>> m = re.search(r"a(z)?", "ab")
>>> type(m.lastindex)


>>> m = re.match(r"(w+) (w+)(d)?", "Isaac Newton, physicist")
>>> m.lastindex
2

Match.lastgroup:具有匹配值的最后一个分组的名称,如果没有命名分组或没有任何分组匹配,返回None

Match.re:创建当前Match对象的Pattern对象

Match.string:进行匹配的原始字符串

3.7版本re模块新特性

Non-empty matches can now start just after a previous empty match:

# python3.7之前
>>> re.sub("x*", "-", "abxd")
"-a-b-d-"

# python3.7
>>> re.sub("x*", "-", "abxd")
"-a-b--d-"

Unknown escapes in repl consisting of "" and an ASCII letter now are errors:

# python3.7之前
>>> print(re.sub(r"w+", r"d", "ab&xd&"))
d&d&

# python3.7
>>> print(re.sub(r"w+", r"d", "ab&xd&"))
...
re.error: bad escape d at position 0

Only characters that can have special meaning in a regular expression are escaped:

# python3.7之前
>>> print(re.escape("!#$%&"))
!#$\%&

# python3.7
>>> print(re.escape("!#$%&"))
!#$%&

Added support of splitting on a pattern that could match an empty string:

# python3.7之前
>>> re.split(r"", "Words, words, words.")
...
ValueError: split() requires a non-empty pattern match.

>>> re.split(r"W*", "...words...")
["", "words", ""]

>>> re.split(r"(W*)", "...words...")
["", "...", "words", "...", ""]

# python3.7
>>> re.split(r"", "Words, words, words.")
["", "Words", ", ", "words", ", ", "words", "."]

>>> re.split(r"W*", "...words...")
["", "", "w", "o", "r", "d", "s", "", ""]

>>> re.split(r"(W*)", "...words...")
["", "...", "", "", "w", "", "o", "", "r", "", "d", "", "s", "...", "", "", ""]

Added support of copy.copy() and copy.deepcopy(). Match objects are considered atomic

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/43511.html

相关文章

  • Python 正则达式

    摘要:今天就专门看看正则表达式。下面是一个正则表达式最简单的使用例子。这个例子使用了正则表达式模块的函数,它会返回所有符合模式的列表。查询标志让正则表达式具有不同的行为。,按给定正则表达式分割字符串。,正则表达式中捕获组的数量。 最近研究Python爬虫,很多地方用到了正则表达式,但是没好好研究,每次都得现查文档。今天就专门看看Python正则表达式。本文参考了官方文档 re模块。 模式 首...

    FrancisSoung 评论0 收藏0
  • Python基础教程:-正则达式基本语法以及re模块

    摘要:正则表达式关闭或可选标志。如果所含正则表达式,以表示,在当前位置成功匹配时成功,否则失败。否则指的是八进制字符码的表达式。 正则表达式是个很牛逼的东西,不管是在javascript,还是在Python web开发(http://www.maiziedu.com/course/python-px...)中,我们都会遇到正则表达式,虽然javascript和Python的正则表达式区别不大...

    y1chuan 评论0 收藏0
  • Python正则达式保姆式教学,带你精通大名鼎鼎的正则

    摘要:今天来给大家分享一份关于比较详细的正则表达式宝典,学会之后你将对正则表达式达到精通的状态。正则表达式是用在方法当中,大多数的字符串检索都可以通过来完成。导入模块在使用正则表达式之前,需要导入模块。 ...

    tulayang 评论0 收藏0
  • Python 正则达式 re 模块简明笔记

    摘要:假设现在想把字符串你好,,世界中的中文提取出来,可以这么做你好,,世界注意到,我们在正则表达式前面加上了两个前缀,其中表示使用原始字符串,表示是字符串。本文标题为正则表达式模块简明笔记本文链接为参考资料正则表达式 简介 正则表达式(regular expression)是可以匹配文本片段的模式。最简单的正则表达式就是普通字符串,可以匹配其自身。比如,正则表达式 hello 可以匹配字符...

    lastSeries 评论0 收藏0
  • 众里寻她千百度--正则达式

    摘要:如果经过一系列输入,最终如果能达到状态,则输入内容一定满足正则表达式。正则表达式可以转换为,已经有成熟的算法实现这一转换。不过有时候转换为可能导致状态空间的指数增长,因此直接用识别正则表达式。 原文地址 先来看一个让人震撼的小故事,故事来自知乎问题PC用户的哪些行为让你当时就震惊了? 同学在一个化妆品公司上班,旁边一个大妈(四十多岁)发给他一个exl表,让他在里面帮忙找一个经销商的资料...

    golden_hamster 评论0 收藏0

发表评论

0条评论

Cheriselalala

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<