zoukankan      html  css  js  c++  java
  • python学习之正则表达式

    python的re模块提供了有关正则表达式的方法。

    常用方法与属性:

    compile(pattern,flags=0) ---- 返回一个正则表达式对象,也就是说生成一个正则表达式模板,在多次使用同一个表达式的时候这个方法可以提高效率;

    search(pattern,string,flags=0)-----返回一个match 对象;

    match(pattern,string,flags=0)-----返回一个match对象;

        search与match的区别是:match是从string的第一个字符开始匹配,如若第一个字符串没有匹配到,则返回None。search是对string的任何位置进行匹配。

    sub(pattern,repl,string, count=0, flags=0);pattern参数是正则表达式;repl参数是匹配之后所需要替换的,可以是字符串或者函数;string参数是目标字符串。

        -----返回的是一个新字符串;

    subn(pattern,repl,string, count=0flags=0) -----返回的是一个tuple(new_string,number_of_subs_mode);

    purge() -----清除正则表达式缓存;

    escape()-------对字符串中的非字母数字进行转义;

    split(pattern,string,count=0,flags=0) ----根据pattern在string匹配,并在匹配处对string进行分割,返回的是一个list,list里面包含分割后的字符串集合;

    ====================================================================================

    正则表达式对象(Regular Expression Objects)

    一般通过re.compile(pattern)得到一个正则表达式对象;

    常用方法:

    search(string[,pos[,endpos]]) ----返回一个match对象。

    match(string[,pos[,endpos]]) ----返回一个match对象。

    split(string)-----利用模板对字符串进行分割;

    sub(repl,string,count=0)

    subn(repl,string,count=0)

    ============================================================

    Match对象

    可以利用re.match()或者re.search()得到一个match对象;

    常用方法:

    .group()----返回match对象的匹配结果

    .groups()---返回匹配之后的元组

    groupdict()----返回一个dict.这个结合pattern,比较灵活;

    1 m = re.match(r"(?P<first_name>w+) (?P<last_name>w+)", "Malcolm Reynolds")
    2  m.groupdict()
    View Code

    start([group])

    end([group])

    email = "tony@tiremove_thisger.net"
    m = re.search("remove_this", email)
    email[:m.start()] + email[m.end():]

    输出:'tony@tiger.net'

    span([group])------返回一个tuple(起始,结束);

    一般在写正则表达式的时候我们习惯  r'正则' ,省去了好多的转义。

  • 相关阅读:
    Centos7 安装RabbitMQ 3.6.1
    面向对象编程(类的绑定方法与非绑定方法)
    面向对象编程(封装、封装的意义、封装与扩展性、@property)
    函数式编程(__slots__)
    面向对象编程(实例属性、类属性)
    面向对象编程(获取对象信息)
    面向对象编程(继承、多态)
    函数式编程(访问限制)
    面向对象编程(类与实例)
    面向对象编程(基础简介)
  • 原文地址:https://www.cnblogs.com/hf-china/p/5109585.html
Copyright © 2011-2022 走看看