re的使用

  1. 数量词的贪婪模式与非贪婪模式
    正则表达式通常用于在文本中查找匹配的字符串,Python里数量词默认是贪婪的,总是尝试匹配尽可能多的字符;加问号可以变成非贪婪
    例:如果查找abbbc,“ab*”的结果是abbb,而“ab*?”的结果是ab
  2. 常用方法
  • re.match
    • 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none
    • 函数语法:re.match(pattern,string,flags=0)
    str1="I study python3.6 Everyday"
    m1=re.match(r'\w',str1)
    m1=re.match(r'i',str1,re.I)
    print(m1.group())
    
  • re.sub
    • 替换字符串,re.sub(pattern,replace,string)
    su1=re.sub(r'<div>(.+)</div>',r'<span>\1</span>',str2)
    print(su1)
    
  • re.findall
    • 查找全部,re.findall(pattern,string,flags=0)
    f1.findall(r'y',str1)//['y','y','y','y']
    str2='<div><a href="http://www.baidu.com">西邮xupt</a></div>'
    t1.findall(r'<a href="(.+)">',str2)//http://www.baidu.com
    
  • re.search
    s1.search(r's\w+',str1)//study
    s2.search(r'p\w+.\d',str1)//python3.6
    s3.search(r'study',str1)//study
    print(s1.group())
    

猜你喜欢

转载自blog.csdn.net/qq_41386300/article/details/83154960
re