正则表达式
许多程序设计语言都支持利用正则表达式进行字符串操作。在python中需要通过正则表达式对字符串进行匹配的时候,可以使用re模块。re模块使python语言拥有全部的正则表达式功能。
特点:
一、python中的正则表达式
print(re.match(‘\\\\‘,‘\hello‘)) #需要使用4个反斜杠来匹配一个
python里的原生字符串很好地解决了这个问题,有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。在python字符串前面添加 r 即可将字符串转换为原生字符串。(r:raw string)
print(re.match(r‘\\‘,‘\hello‘)) #使用两个反斜杠即可匹配一个
一个例子:
import re x=‘hello\\nworld‘ #hello\nworld #在正则表达式里,如果想要匹配一个 \ ,需要使用\\\#第一个参数就是正则匹配规则 #第二个参数表示需要匹配的字符串 #m=re.search(‘\\\\‘,x) match和search #还可以在字符串前面加r,\\就表示m=re.search(r‘\\‘,x) #search和match方法的执行结果是一个Match类型的对象 print(m) #<re.Match object; span=(5, 6), match=‘\\‘>
二、查找方法的使用
search方法(扫描整个字符串,找到第一个匹配)
finditer方法(扫描整个字符串,找到所有的匹配,并返回要给可迭代对象)
re.match尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回None。
re.match(pattern,string,flags=0)
参数
|
描述
|
pattern
|
匹配的正则表达式
|
string
|
要匹配的字符串
|
flags
|
标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等。
|
使用group(num)函数来获取匹配表达式
import re result1=re.match(r‘He‘,‘Hello‘) result2=re.match(r‘e‘,‘Hello‘) print(result1.group(0)) # ‘He‘ 匹配到的元素 print(result1.span()) # (0, 2) 匹配元素的位置,从0位到1位,2不包括内 print(result2) # None 没匹配到
2、search方法的使用
re.search(pattern,string,flags=0)
应用:
import re result1=re.search(r‘he‘,‘hello‘) result2=re.search(r‘lo‘,‘hello‘) print(result1.group(0)) #he print(result1.span()) #(0,2) print(result2.group(0)) #lo print(result2.span()) #(3,5) 不包括第5位
re.match与re.search的区别
import re result1=re.search(r‘天气‘,‘今天天气真好!‘) result2=re.match(r‘天气‘,‘今天天气真好!‘) print(result1) # <re.Match object; span=(2, 4), match=‘天气‘> print(result2) # None
3、findall方法的使用
re.findall(pattern,string,flags=0)
应用:
ret=re.findall(r‘\d+‘,‘h12ab34‘) print(ret) #[‘12‘, ‘34‘] ret=re.match(r‘\d+‘,‘h12ab34‘) print(ret) #None match只匹配开头,所以没匹配到 ret=re.search(r‘\d+‘,‘h12ab34‘) print(ret) #<re.Match object; span=(0, 2), match=‘12‘> 只匹配一次
4、finditer方法的使用
from collections.abc import Iterable mm=re.finditer(r‘c‘,‘agcegcklclexce9‘) print(isinstance(mm, Iterable)) #True for m in mm: print(m) #<re.Match object; span=(2, 3), match=‘c‘> #<re.Match object; span=(5, 6), match=‘c‘> #<re.Match object; span=(8, 9), match=‘c‘> #<re.Match object; span=(12, 13), match=‘c‘> for m in mm: print(m.group(),m.span()) #匹配对象里的group保存了匹配的结果 #c (2, 3) #c (5, 6) #c (8, 9) #c (12, 13)
5、fullmatch方法的使用
m4=re.fullmatch(r‘he‘,‘hello‘) #None m4=re.fullmatch(r‘hello‘,‘hello‘) #<re.Match object; span=(0, 5), match=‘hello‘>
原文:https://www.cnblogs.com/shixiaoxun/p/14528619.html