正则表达式(Regular Expression)
正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个"规则字符串",这个"规则字符串"用来表达对字符串的一种过滤逻辑。正则表达式是一种文本模式,该模式描述在搜索文本时要匹配的一个或多个字符串。它本身是一种小型的、高度专业化的编程语言,在python中,通过内嵌集成re模块,根据代码可以直接调用来实现正则匹配。正则表达式模式被编译成一系列的字节码,然后由用C编写的匹配引擎执行。
import re
python re库文件常用函数介绍:
# 通过以下命令查看简介
help(re.match)
help(re.search)
help(re.findall)
help(re.compile)
Help on function match in module re:
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.
Help on function search in module re:
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.
Help on function findall in module re:
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.
Help on function compile in module re:
compile(pattern, flags=0)
Compile a regular expression pattern, returning a pattern object.
re.match函数作用:
尝试从字符串的开头开始匹配一个模式,如果匹配成功,返回一个匹配成功的对象,否则返回None。
re.match函数参数说明:
pattern:匹配的正则表达式
string:要匹配的字符串
flags:标志位,用于控制正则表达式的匹配方式。如是否区分大小写、是否多行匹配等。
re.search函数作用:
扫描整个字符串并返回第一次成功的匹配对象,如果匹配失败,则返回None。
re.search函数参数说明:
pattern:匹配的正则表达式
string:要匹配的字符串
flags:标志位,用于控制正则表达式的匹配方式。如是否区分大小写、是否多行匹配等。
re.findall函数的作用:
获取整个字符串中所有匹配的字符串,并以列表的形式返回。列表中的元素有如下几种情况:
当正则表达式中含有多个圆括号()时,列表的元素为多个字符串组成的元组,而且元组中字符串个数与括号对数相同,并且字符串排放顺序跟括号出现的顺序一致,当正则表达式中没有圆括号时,列表中的字符串表示整个正则表达式匹配的内容。
这里的()主要是提取相关字符的作用,返回的值为列表形式。
re.findall函数参数说明:
pattern:匹配的正则表达式
string:被分割的字符串
flags:标志位,用于控制正则表达式的匹配方式。如是否区分大小写、是否多行匹配等。
re.compile函数的作用:
返回的是一个匹配对象,单独使用就无任何意义,需要和findall(), search(), match()搭配使用。
使用方式:
import re
text = 'abcde12345edcba'
regex = re.compile(r'([a-z]*)([0-9]*)([a-z]*)')
result = regex.search(text)
print(result.group(