python正则表达式
2021/12/14 17:16:43
本文主要是介绍python正则表达式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
python正则表达式,要先导入re的包
re模块使python语言拥有了全部的正则表达式的功能
compile函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象,该对象拥有一系列方法
re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match() 就返回 none
match方法
接span可以查看跨度,以元组形式展示
re.match(pattern, string, flags=0)
方法名称 | 作用 |
---|---|
group | 以str形式返回对象中match的元素 |
start | 返回开始位置 |
end | 返回结束位置 |
span | 以tuple形式返回范围 |
#!/usr/bin/python # -*- coding: UTF-8 -*- import re print(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配 print(re.match('kkk', 'www.runoob.com')) # 不在起始位置匹配
#!/usr/bin/python import re line = "Cats are smarter than dogs" matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) if matchObj: print "matchObj.group() : ", matchObj.group() print "matchObj.group(1) : ", matchObj.group(1) print "matchObj.group(2) : ", matchObj.group(2) # print "matchObj.group(3) : ", matchObj.group(3) else: print "No match!!"
matchObj.group() : Cats are smarter than dogs matchObj.group(1) : Cats matchObj.group(2) : smarter
search方法
re.search扫描整个字符串并返回第一个成功的匹配
re.search(pattern, string, flags=0)
#!/usr/bin/python # -*- coding: UTF-8 -*- import re print(re.search('www', 'www.runoob.com').span()) # 在起始位置匹配 print(re.search('com', 'www.runoob.com').span()) # 不在起始位置匹配
(0, 3) (11, 14)
从这可以看出match和search方法的不同
re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
替换
re.sub(pattern, repl, string, count=0, flags=0)
- pattern : 正则中的模式字符串。
- repl : 替换的字符串,也可为一个函数。
- string : 要被查找替换的原始字符串。
- count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。
#!/usr/bin/python # -*- coding: UTF-8 -*- import re phone = "2004-959-559 # 这是一个国外电话号码" # 删除字符串中的 Python注释 num = re.sub(r'#.*$', "", phone) print "电话号码是: ", num # 删除非数字(-)的字符串 num = re.sub(r'\D', "", phone) print "电话号码是 : ", num
电话号码是: 2004-959-559 电话号码是 : 2004959559
#!/usr/bin/python # -*- coding: UTF-8 -*- import re # 将匹配的数字乘以 2 def double(matched): value = int(matched.group('value')) return str(value * 2) s = 'A23G4HFD567' print(re.sub('(?P<value>\d+)', double, s))
(?P<value>\d+)现在不这样写了,一般直接写(?<value>\d+),意思是把数字放到一个叫value的组中
compile函数
compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用
findall函数
# -*- coding:UTF8 -*- import re pattern = re.compile(r'\d+') # 查找数字 result1 = pattern.findall('runoob 123 google 456') result2 = pattern.findall('run88oob123google456', 0, 10) print(result1) print(result2)
['123', '456'] ['88', '12']
finditer
和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回
这篇关于python正则表达式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python