match、search、findall、finditer、compile、spilt正则表达式

简单记录对于正则表达式的使用

对于match、search、findall、finditer、compile如何使用正则表达式


match

正则匹配开始字符串,成功则返回正则一个匹配对象,没有匹配成功则返回None

  • Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found
import re

message="Tue Apr 30 05:16:30 EDT 2019"
"""match"""
matchNumber=re.match('\d{2}', message)
print(matchNumber)
if matchNumber is not None:
    print(matchNumber.group())

matchNumber=re.match('\w{2}', message)
print(matchNumber)
if matchNumber is not None:
    print(matchNumber.group())
None
<re.Match object; span=(0, 2), match='Tu'>
Tu

fullmatch

fullmatch 正则表达式模式与所有字符串匹配。

  • fullmatch Match a regular expression pattern to all of a string.
"""fullmatch"""
message = "Tue Apr 30 05:16:30 EDT 2019"
matchNumber = re.fullmatch('\w{3}', message)
print(matchNumber)
if matchNumber is not None:
    print(matchNumber.group())
matchNumber = re.fullmatch('Tue Apr', message)
print(matchNumber)
if matchNumber is not None:
    print(matchNumber.group())
matchNumber = re.fullmatch('.*', message)
print(matchNumber)
if matchNumber is not None:
    print(matchNumber.group())
None
None
<re.Match object; span=(0, 28), match='Tue Apr 30 05:16:30 EDT 2019'>
Tue Apr 30 05:16:30 EDT 2019


search

正则搜索字符串,搜索成功则返回一个正则匹配对象,没有成功则返回None

  • Scan through string looking for a match to the pattern, returning a Match object, or None if no match was found.
  • 和match的区别是,match是开始字符匹配。
import re
#"""search"""
message="Tue Apr 30 05:16:30 EDT 2019"
matchNumber=re.search('\d{2}', message)
print(matchNumber)
if matchNumber is not None:
    print(matchNumber.group())

matchNumber=re.search('\w{2}', message)
print(matchNumber)
if matchNumber is not None:
    print(matchNumber.group())

matchNumber=re.search('\d{6}', message)
print(matchNumber)
if matchNumber is not None:
    print(matchNumber.group())
<re.Match object; span=(8, 10), match='30'>
30
<re.Match object; span=(0, 2), match='Tu'>
Tu
None

findall

查找字符串中出现的所有模式,返回一个列表

  • Find all occurrences of a pattern in a string
"""findall"""
message = "Tue Apr 30 05:16:30 EDT 2019"

message = "Tue Apr 30 05:16:30 EDT 2019"
matchNumber = re.findall('\w{3}', message)
print(matchNumber)
print(type(matchNumber))
if matchNumber is not None:
    for i in matchNumber:
        print(i)
['Tue', 'Apr', 'EDT', '201']
<class 'list'>
Tue
Apr
EDT
201

finditer

返回一个迭代器,为每个匹配产生一个正则对象

  • Return an iterator yielding a Match object for each match
"""finditer"""
message = "Tue Apr 30 05:16:30 EDT 2019"

message = "Tue Apr 30 05:16:30 EDT 2019"
matchNumber = re.finditer('\w{3}', message)
print(matchNumber)
print(type(matchNumber))
#方法一
try:
    while True:
        print(next(matchNumber).group())  #正则对象用group
except StopIteration:
    pass
#方法二
for i in matchNumber:
    print(i.group())
<callable_iterator object at 0x7f571dfe9390>
<class 'callable_iterator'>
Tue
Apr
EDT
201

compile

将模式编译为Pattern对象。预编译,多次使用的预编译

  • Compile a pattern into a Pattern object.
"""compile"""

message = "Tue Apr 30 05:16:30 EDT 2019"
reg = re.compile("/d{2}")
result = reg.match(message)
print(result)
reg = re.compile("[a-zA-Z]{3}")
result = reg.match(message)
print(result)
None
<re.Match object; span=(0, 3), match='Tue'>

sub

查找替换

  • Substitute occurrences of a pattern found in a string.
import re

message="Tue Apr 30 06:41:20 EDT 2019"

"""replace"""
"""简单文本"""

print(message)
print(message.replace("Apr", "四月"))
reg = re.compile("\d")
print(reg.sub("G", message))
Tue Apr 30 06:41:20 EDT 2019
Tue 四月 30 06:41:20 EDT 2019
Tue Apr GG GG:GG:GG EDT GGGG

subn

查看替换,返回一个带有替换个数的元组

  • Same as sub, but also return the number of substitutions made.
import re
message="Tue Apr 30 06:41:20 EDT 2019"

"""replace"""
"""简单文本"""

print(message)
print(message.replace("Apr", "四月"))
reg = re.compile("\d")
print(reg.subn("G", message))
Tue Apr 30 06:41:20 EDT 2019
Tue 四月 30 06:41:20 EDT 2019
('Tue Apr GG GG:GG:GG EDT GGGG', 12)

正则

FACTION

        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

特殊字符

    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) Set the A, I, L, M, S, U, or X flag for the RE (see 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.

转义

        \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.

该模块中的一些函数将标志作为可选参数:

        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.

参考文档

参考文档

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,386评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,142评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,704评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,702评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,716评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,573评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,314评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,230评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,680评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,873评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,991评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,706评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,329评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,910评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,038评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,158评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,941评论 2 355

推荐阅读更多精彩内容

  • #首先,python中的正则表达式大致分为以下几部分: 元字符 模式 函数 re 内置对象用法 分组用法 环视用法...
    mapuboy阅读 1,610评论 0 51
  • re模块手册 本模块提供了和Perl里的正则表达式类似的功能,不关是正则表达式本身还是被搜索的字符串,都可以...
    喜欢吃栗子阅读 4,009评论 0 13
  • 01.正则基本符号 1.什么是正则表达式 正则表达式就是字符匹配的工具;是由正则符号和普通字符组成,来匹配不同规律...
    Gary134阅读 532评论 0 0
  • 现代的职业分工已经很细,我们基本上只能在一个行业里成为专家。 有一点我们需要记住,这个世界上,有史以来,直到我们看...
    西西弗斯XD阅读 494评论 1 1
  • 很多时候,我们会感觉到很快乐。 但是... 快乐真的只是一种心情吗? 我们常常发现,善良的人更容易快乐。 善良的人...
    草帽会客厅阅读 770评论 1 3