本篇文章给大家带来的内容是关于python中正则表达式的详细介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
正则
re = regular experssion
re 模块使 Python 语言拥有全部的正则表达式功能。
compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。
作用: 对于字符串进行处理, 会检查这个字符串内容是否与你写的正则表达式匹配
如果匹配, 拿出匹配的内容;
如果不匹配, 忽略不匹配内容;
编写正则的规则
pattern 匹配的正则表达式
string 要匹配的字符串
三种查找方法
1). findall
import restr = 'hello sheen,hello cute.'pattern_1 = r'hello'pattern_2 = r'sheen'print(re.findall(pattern_1,str)) #['hello', 'hello']print(re.findall(pattern_2,str)) #['sheen']
2).match
match尝试从字符串的起始位置开始匹配,
-
如果起始位置没有匹配成功, 返回一个None;
-
如果起始位置匹配成功, 返回一个对象;
import restr = 'hello sheen,hello cute.'pattern_1 = r'hello'pattern_2 = r'sheen'print(re.match(pattern_1,str)) #<_sre.SRE_Match object; span=(0, 5), match='hello'>print(re.match(pattern_1,str).group()) #返回match匹配的字符串内容,helloprint(re.match(pattern_2,str)) #None
3).search
search会扫描整个字符串, 只返回第一个匹配成功的内容;
-
如果能找到, 返回一个对象, 通过group方法获取对应的字符串;
import restr = 'hello sheen,hello cute.'pattern_1 = r'hello'pattern_2 = r'sheen'print(re.search(pattern_1,str)) #<_sre.SRE_Match object; span=(0, 5), match='hello'>print(re.search(pattern_1,str).group()) #helloprint(re.search(pattern_2,str)) #<_sre.SRE_Match object; span=(6, 11), match='sheen'>print(re.search(pattern_2,str).group()) #sheen
特殊字符类
.: 匹配除了\n之外的任意字符; [.\n]
\d: digit–(数字), 匹配一个数字字符, 等价于[0-9]
\D: 匹配一个非数字字符, 等价于[^0-9]
\s: space(广义的空格: 空格, \t, \n, \r), 匹配单个任何的空白字符;
\S: 匹配除了单个任何的空白字符;
\w: 字母数字或者下划线, [a-zA-Z0-9_]
\W: 除了字母数字或者下划线, [^a-zA-Z0-9_]
import re# .print(re.findall(r'.','sheen\nstar\n')) #['s', 'h', 'e', 'e', 'n', 's', 't', 'a', 'r']#\d#\Dprint(re.findall(r'\d','当前声望30')) #['3', '0']print(re.findall(r'\D','当前声望30')) #['当', '前', '声', '望']#\s#\Sprint(re.findall(r'\s', '\n当前\r声望\t为30')) #['\n', '\r', '\t']print(re.findall(r'\S', '\n当前\r声望<span>本文来源gaodai#ma#com搞*代#码9网#</span>\t为30')) #['当', '前', '声', '望', '为', '3', '0']#\w#\Wprint(re.findall(r'\w','lucky超可爱!!')) #['l', 'u', 'c', 'k', 'y', '超', '可', '爱']print(re.findall(r'\W','lucky超可爱!!')) #['!', '!']