python 正则表达式

来源:互联网 发布:想学电脑编程 编辑:程序博客网 时间:2024/06/11 08:13

正则表达式简介:正则表达式是用于处理字符串的强大工具,拥有自己独特的语法以及一个独立的处理引擎,效率上可能不如str自带的方法,但功能十分强大。得益于这一点,在提供了正则表达式的语言里,正则表达式的语法都是一样的,区别只在于不同的编程语言实现支持的语法数量不同;但不用担心,不被支持的语法通常是不常用的部分。如果已经在其他语言里使用过正则表达式,只需要简单看一看就可以上手了。

re 模块使 Python语言拥有全部的正则表达式功能。

re 模块也提供了与这些方法功能完全一致的函数,这些函数使用一个模式字符串做为它们的第一个参数。

compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。

术语:匹配(matching)指模式匹配(pattern-matching),python专门术语中,有两种主要方法完成模式匹配:搜索(searching)和匹配(matching)

搜索:即在字符串任意部分中搜索匹配的模式,通过search()函数或方法实现;

匹配:判断一个字符串能否从起始处全部或部分的匹配某个模式,调用match()方法或函数方法实现.

match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

 主要的方法(源码):

def match(pattern, string, flags=0):  # 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none    """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)
    # pattern匹配的正则表达式
    # string要匹配的字符串
    # flags标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等
    # 匹配成功re.match方法返回一个匹配的对象,否则返回None。    # 我们可以使用group(num) 或 groups() 匹配对象函数来获取匹对象函数来获取匹配表达式

    # group(num=0)匹配的整个表达式的字符串,group() 可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。    # groups()返回一个包含所有小组字符串的元组,从 1 到 所含的小组号。
    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): # re.search 扫描整个字符串并返回第一个成功的匹配。   re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配    """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)
    # pattern匹配的正则表达式    # string要匹配的字符串。    # flags标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。    # 匹配成功re.search方法返回一个匹配的对象,否则返回None。    # 我们可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。    # group(num=0)匹配的整个表达式的字符串,group() 可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。    # groups()返回一个包含所有小组字符串的元组,从 1 到 所含的小组号。 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)    # pattern : 正则中的模式字符串。    # repl : 替换的字符串,也可为一个函数。    # string : 要被查找替换的原始字符串。    # count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。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()    _cache_repl.clear()def template(pattern, flags=0):    "Compile a template pattern, returning a pattern object"    return _compile(pattern, flags|T)

语法:

importre#导入模块名
 
p = re.compile("^[0-9]"#生成要匹配的正则对象, ^代表从开头匹配,[0-9]代表匹配0至9的任意一个数字, 所以这里的意思是对传进来的字符串进行匹配,如果这个字符串的开头第一个字符是数字,就代表匹配上了
 
m = p.match('14534Abc')  #按上面生成的正则对象去匹配 字符串, 如果能匹配成功,这个m就会有值, 否则m为None<br><br>if m: #不为空代表匹配上了
print(m.group())#m.group()返回匹配上的结果,此处为1,因为匹配上的是1这个字符<br>else:<br>  print("doesn't match.")<br>

也可以这样写

m = p.match("^[0-9]",'14534Abc')

效果是一样的,区别在于,第一种方式是提前对要匹配的格式进行了编译(对匹配公式进行解析),这样再去匹配的时候就不用在编译匹配的格式,第2种简写是每次匹配的时候要进行一次匹配公式的编译,所以,如果你需要从一个5w行的文件中匹配出所有以数字开头的行,建议先把正则公式进行编译再匹配,这样速度会快点。

匹配格式:

模式

描述

^

匹配字符串的开头

$

匹配字符串的末尾。

.

匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符。

[...]

用来表示一组字符,单独列出:[amk]匹配 'a''m''k'

[^...]

不在[]中的字符:[^abc]匹配除了a,b,c之外的字符。

re*

匹配0个或多个的表达式。

re+

匹配1个或多个的表达式。

re?

匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式

re{ n}

 

re{ n,}

精确匹配n个前面表达式。

re{ n, m}

匹配 n m次由前面的正则表达式定义的片段,贪婪方式

a| b

匹配ab

(re)

G匹配括号内的表达式,也表示一个组

(?imx)

正则表达式包含三种可选标志:i, m, x。只影响括号中的区域。

(?-imx)

正则表达式关闭 i, m, x可选标志。只影响括号中的区域。

(?: re)

类似 (...),但是不表示一个组

(?imx: re)

在括号中使用i, m, x可选标志

(?-imx: re)

在括号中不使用i, m, x可选标志

(?#...)

注释.

(?= re)

前向肯定界定符。如果所含正则表达式,以 ...表示,在当前位置成功匹配时成功,否则失败。但一旦所含表达式已经尝试,匹配引擎根本没有提高;模式的剩余部分还要尝试界定符的右边。

(?! re)

前向否定界定符。与肯定界定符相反;当所含表达式不能在字符串当前位置匹配时成功

(?> re)

匹配的独立模式,省去回溯。

\w

匹配字母数字

\W

匹配非字母数字

\s

匹配任意空白字符,等价于 [\t\n\r\f].

\S

匹配任意非空字符

\d

匹配任意数字,等价于 [0-9].

\D

匹配任意非数字

\A

匹配字符串开始

\Z

匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串。c

\z

匹配字符串结束

\G

匹配最后匹配完成的位置。

\b

匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er\b'可以匹配"never"中的 'er',但不能匹配 "verb"中的 'er'

\B

匹配非单词边界。'er\B'能匹配 "verb"中的 'er',但不能匹配 "never"中的 'er'

\n, \t, .

匹配一个换行符。匹配一个制表符。等

\1...\9

匹配第n个分组的子表达式。

\10

匹配第n个分组的子表达式,如果它经匹配。否则指的是八进制字符码的表达式。

 

修饰符 - 可选标志:

修饰符描述re.I使匹配对大小写不敏感re.L做本地化识别(locale-aware)匹配re.M多行匹配,影响 ^ 和 $re.S使 . 匹配包括换行在内的所有字符re.U根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.re.X该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。


正则表达式常用5种操作:

re.match(pattern, string) #从头匹配

re.search(pattern, string)匹配整个字符串,直到找到一个匹配

re.split() #将匹配到的格式当做分割点对字符串分割成列表

 

re.split示例:

import rem = re.split("[0-9]", "alex1rain2jack3helen rachel8")print(m)### 输出结果['alex', 'rain', 'jack', 'helen rachel', '']

 

re.findall()      # 找到所有要匹配的字符并返回列表格式

import rem = re.findall("[0-9]", "alex1rain2jack3helen rachel8")print(m)### 输出结果['1', '2', '3', '8']


re.sub(pattern, repl, string, count,flag) 
#替换匹配到的字符

import rem=re.sub("[0-9]","|", "alex1rain2jack3helen rachel8",count=2 )print(m)### 输出结果alex|rain|jack3helen rachel8


正则表达式实例:

字符匹配

实例

描述

python

匹配 "python".

字符类

实例

描述

[Pp]ython

匹配 "Python" "python"

rub[ye]

匹配 "ruby" "rube"

[aeiou]

匹配中括号内的任意一个字母

[0-9]

匹配任何数字。类似于 [0123456789]

[a-z]

匹配任何小写字母

[A-Z]

匹配任何大写字母

[a-zA-Z0-9]

匹配任何字母及数字

[^aeiou]

除了aeiou字母以外的所有字符

[^0-9]

匹配除了数字外的字符

特殊字符类

实例

描述

.

匹配除 "\n"之外的任何单个字符。要匹配包括 '\n'在内的任何字符,请使用象 '[.\n]'的模式。

\d

匹配一个数字字符。等价于 [0-9]

\D

匹配一个非数字字符。等价于 [^0-9]

\s

匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]

\S

匹配任何非空白字符。等价于 [^ \f\n\r\t\v]

\w

匹配包括下划线的任何单词字符。等价于'[A-Za-z0-9_]'

\W

匹配任何非单词字符。等价于 '[^A-Za-z0-9_]'

 

常见的正则例子:

匹配手机号

phone_str = "hey my name is test, and my phone number is 13333242323, please call me if you are pretty!"phone_str2 = "hey my name is test, and my phone number is 18651154604, please call me if you are pretty!"m = re.search("(1)([358]\d{9})",phone_str2)if m:    print(m.group())### 输出结果18651154604

 

匹配ipv4

ip_addr = "inet 192.168.60.223 netmask 0xffffff00 broadcast 192.168.60.255"m = re.search("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", ip_addr)print(m.group())### 输出结果192.168.60.223

 

分组匹配地址:

m = re.match('(\w\w\w)-(\d\d\d)','abc-123')print(m.group())    ### 所有匹配部分print(m.group(1))    ### 匹配子组1print(m.group(2))    ### 匹配子组2print(m.groups())    ### 所有的匹配子组###输出结果
abc-123abc123('abc', '123')

 

匹配email

email = "constant_zyh@126.com   http://www.oldboyedu.com"m = re.search(r"[0-9.a-z]{0,26}@[0-9.a-z]{0,20}.[0-9a-z]{0,8}", email)print(m.group())### 输出结果constant_zyh@126.com

 

 

 

1 0
原创粉丝点击