python基础:8.正则表达式

1.概念

正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串”用来表达对字符串的一种过滤逻辑。

re模块的常见方法:

1.  re.findall("RegexExpression", "str")     #  返回一个列表,列表可为空

例如:

1 string_a = '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">\n\t\t<meta http-equiv="content-type" content="text/html;charset=utf-8">\n\t\t<meta content="always" name="referrer">\n        <meta name="theme-color" content="#2932e1">'
2 ret = re.findall("<.*>",string_a)
3 print(ret)
4 
5 
6 # 结果
7 
8 ['<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">', '<meta http-equiv="content-type" content="text/html;charset=utf-8">', '<meta content="always" name="referrer">', '<meta name="theme-color" content="#2932e1">']

2. pattern.match("RegexExpression", "str")从头匹配,直到不符合正则表达式结束  #  

import re

string_a = '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">\n\t\t<meta http-equiv="content-type" content="text/html;charset=utf-8">\n\t\t<meta content="always" name="referrer">\n        <meta name="theme-color" content="#2932e1">'
ret = re.match("[^\d]+" ,string_a)
print(ret)


# 结果,为什么匹配到g就失败了呢,

<re.Match object; span=(0, 59), match='<meta http-equiv="X-UA-Compatible" content="IE=ed>
原文地址:https://www.cnblogs.com/meloncodezhang/p/11296319.html