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

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

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())

30

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']

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())


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


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...) 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).
        (?

转义

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

参考文档

参考文档

你可能感兴趣的:(match、search、findall、finditer、compile、spilt正则表达式)