RE模块-正则表达式

Menu

  • re定义
  • re元字符
  • re方法

re定义
  • 正则表达式本身是一种小型的、高度专业化的编程语言,而在python中,通过内嵌集成re模块,程序媛们可以直接调用来实现正则匹配。正则表达式模式被编译成一系列的字节码,然后由用C编写的匹配引擎执行,执行速度快。他定义了在其它字符串中进行匹配的模式(进行模糊查询的方式)。

re元字符
  • . ^ $ * + ? {} [] | () \

  • . 通配符

result = re.findall("py..on", "aaaapythonbbbpycconccc")        # 通配符
print(result)   # ['python', 'pyccon']
  • ^元字符
result = re.findall("^python", "pythonbbbpycconccc")   # 匹配以什么开头
print(result)   # ['python']
  • $元字符
result = re.findall("python$", "bbbpycconcccpython")   # 匹配以什么结尾
print(result)   # ['python']
  • *元字符
result = re.findall("co*l", "cccoolcccoolccc")  # 匹配0-无限次
print(result)   # ['ccc', 'ccc']
  • +元字符
result = re.findall("w+", "wwwww.abc.com")  # 匹配1-无限次
print(result)   # ['wwwww']
  • ?元字符
result = re.findall("em?", "emmmm~. ")  # ? 匹配0-1次
print(result)   # ['em']
  • {}元字符
result = re.findall("w{1-3}", "wwww.abc.com")  #{n,[n]} 匹配n次 或 n-n次
print(result)   # ['www']
  • [] 字符集
result = re.findall("[a-zA-Z]ython", "Python is a programming language, I am learning python...")    #  [字符集]
print(result)   # ['Python', 'python']
  • | 元字符
result = re.findall("pathon|pbthon|pcthon", "asdfaspathonasdfpbthonasdfpcthonasdf")  # 或者|
print(result)   # ['pathon', 'pbthon', 'pcthon']
  • () 分组符号
  • ()分组把搜索到的内容存到变量里
result = re.search("(?P<name>[a-z]+)(?P<age>[0-9]+)", "bob36smm66cindy5")  
print(result.group("name"))   # bob    
print(result.group("age"))    # 36
  • ()分组里的内容会优先匹配
result = re.findall("www\.(baidu|google)\.com", "www.google.com")
print(result)   # ['google']
  • ()分组里的内容会优先匹配, 如果要取消优先级,需要在括号后加“?:”
result = re.findall("www\.(?:baidu|google)\.com", "www.google.com")
print(result)   # ['www.google.com']
  • ()分组匹配多次
import re
result = re.findall("(?:abc)+", "abcabcabc")  # 如果要分组匹配多次,需要把分组括号括起来加上()+
print(result) #['abcabcabc']   但是有括号,只优先显示括号里的内容,需要取消优先级括号里+"?:"

  • \ 转义符号
"""
\d  匹配任何十进制数;它相当于类 [0-9]。
\D 匹配任何非数字字符;它相当于类 [^0-9]。
\s  匹配任何空白字符;它相当于类 [ \t\n\r\f\v]。
\S 匹配任何非空白字符;它相当于类 [^ \t\n\r\f\v]。
\w 匹配任何字母数字字符;它相当于类 [a-zA-Z0-9_]。
\W 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]
\b  匹配一个特殊字符边界,比如空格 ,&,#等
"""
result = re.findall("\d+", "cc11cool22cccool33ccc")
print(result)   # ['11', '22', '33']
result = re.findall("\D+", "cc11cool22cccool33ccc")
print(result)   # ['cc', 'cool', 'cccool', 'ccc']
result = re.findall("\s+", "cc cool cccool")
print(result)   # [' ', ' ']
result = re.findall("\S+", "cc cool cccool")
print(result)   # ['cc', 'cool', 'cccool']
result = re.findall("\w+", "cc cool cccool _")
print(result)   # ['cc', 'cool', 'cccool', '_']
result = re.findall("\W+", "cc#cool*cccool@")
print(result)   # ['#', '*', '@']
result = re.findall("\\bcool\\b", "cc#cool#cccool#")
print(result)   # ['#', '*', '@']
result = re.findall("c\\\\l", "cc\l#cccool#")  # \\\\转义成\\ , 然后在re模块里再\\转义成\
print(result)   # ['#', '*', '@']

. ^ $ * + ? {} [] | () \

元字符 规则
. 匹配任意除换行符"\n"外的字符(在DOTALL)模式中也能匹配换行符
^ 匹配字符串开头。在多行模式中匹配每一行的开头
$ 匹配字符串末尾,在多行模式中匹配每一行的末尾
* 匹配前一个字符0次或无限次
+ 匹配前一个字符1次或无限次
匹配前一个字符0-1次或
{} 匹配n次 或 n-n次
[] 匹配字符集如[a-zA-Z0-9]
| 匹配|左边或者右边的字符
() 被括起来的表达式将作为分组,从表达式左边开始没遇到一个分组的左括号“(”,编号+1.分组表达式作为一个整体,可以后接数量词。表达式中的 仅在该组中有效。
\ 反斜杠后边跟元字符去除特殊功能,比如\.反斜杠后边跟普通字符实现特殊功能,比如\d

re方法
  • re.findall()
    • 返回所有满足匹配条件的结果,放在列表里
result = re.findall("\d+", "cc11cool22cccool33ccc")
print(result)   # ['11', '22', '33']
  • re.finditer()
    • 返回所有满足匹配条件的结果,返回一个迭代器对象。可以对他进行迭代,一条条处理信息。
result = re.finditer("\d", "sdf878sdfff678zxf000")
print(result)                  # <callable_iterator object at 0x00000000029459B0>
print(next(result).group())    # 8
print(next(result).group())    # 7
  • re.search()
    • 只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
result = re.search("\d+", "cc11cool22cccool33ccc")
print(result.group())   # 11
  • re.match()
    • 同re.search(), 但是仅在开始处开始匹配
result = re.match("\d+", "22cc11cool22cccool33ccc")
print(result.group())   # 22
  • re.split()
    • 如果分割字符串是一个字符集,先按第一个字符分,分出的结果再按第二个字符分。以此类推。
result = re.split("[ab]", "abc")
print(result)   # ['', '', 'c']
  • re.sub()
    • 替换方法,(替换模式,new字符,要替换的字符串)
result = re.sub(pattern="[0-9]", repl="替", string="abc111def222ghi333")
print(result)   # abc替替替def替替替ghi替替替
  • re.subn()
    • 与sub相同的用法,但是会返回一个元组,元组的第二项是替换的次数;
result = re.subn(pattern="[0-9]", repl="替", string="abc111def222ghi333")
print(result)   # ('abc替替替def替替替ghi替替替', 9)
  • re.compile()
    • 保存匹配规则
compile = re.compile("\d+\.\d+")      # 保存匹配规则
print(compile) # re.compile('\\d+\\.\\d+')
result = re.findall(compile, "asdfasdf8.22aasdf3.15")     # 用保存的匹配规则去匹配,可以重复用,维护规则容易
print(result)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python中的re模块--正则表达式 使用match从字符串开头匹配 以匹配国内手机号为例,通常手机号为11位,...
    sunhaiyu阅读 1,008评论 0 2
  • Python中的正则表达式(re) import rere.match #从开始位置开始匹配,如果开头没有则无re...
    BigJeffWang阅读 7,186评论 0 99
  • re模块手册 本模块提供了和Perl里的正则表达式类似的功能,不关是正则表达式本身还是被搜索的字符串,都可以...
    喜欢吃栗子阅读 4,057评论 0 13
  • python的re模块--细说正则表达式 可能是东半球最详细最全面的re教程,翻译自官方文档,因为官方文档写的是真...
    立而人阅读 23,013评论 4 46
  • 两个人总比一个人好,因为二人劳碌同得美好的果效。若是跌倒,这人可以扶起他的同伴;若是孤身跌倒,没有别人扶起他来,这...
    蓝丼阅读 1,254评论 3 5