• 简单理解正则表达式


    我理解的正则表达式:

      正则表达式就是用于字符(串)匹配时的一种描述字符串的表达式。

    关于正则表达式:

    预定义的字符类

    • d可以匹配一个数字;
    • 用D表示非数字字符[^d]
    • w可以匹配一个字母或数字;
    • 用W表示非单词字符[^w]
    • s表示空白字符[空格 fv]
    • S非空白字符[^s]

    数量词

    • .  可以匹配任意除换行( )字符;因此匹配的只能同一行的字符;再点任意匹配模式下可以匹配换行符
    • *表示任意个字符(包括0个);
    • +表示至少一个字符;
    • ?表示0个或1个字符;还可以使 +.*{n,m}数量词变成非贪婪模式
    • {n}表示n个字符;
    • {n,m}表示n-m个字符;
    • 如‘d+-w*s{2-8}w?描述的就是:123-a  2或1-________(_表示空格);

    字符集

    • [0-9a-zA-Z\_]可以匹配一个数字、字母或者下划线;
    • [0-9a-zA-Z\_]+可以匹配至少由一个数字、字母或者下划线组成的字符串,比如'a100''0_Z''Py3000'等等;
    • [a-zA-Z\_][0-9a-zA-Z\_]*可以匹配由字母或下划线开头,后接任意个由一个数字、字母或者下划线组成的字符串,也就是Python合法的变量;
    • [a-zA-Z\_][0-9a-zA-Z\_]{0, 19}更精确地限制了变量的长度是1-20个字符(前面1个字符+后面最多19个字符);
    • A|B可以匹配A或B,所以(A|a)m可以匹配'Am'或者'am';

    边界匹配

    • ^表示行的开头,^d表示必须以数字开头;
    • $表示行的结束,d$表示必须以数字结束;
    • A仅匹配字符串开头
    • 仅匹配字符串末尾
    • 匹配w和W之间的 ???????????????????
    • B    匹配[^]
    • 表示为转义字符,在python的原生字符串r‘’里应用比较直观方便

    Python内的正则表达式运用re模块

    检验正则表达式最好用的函数match()

    • 判断是否匹配,如果匹配成功,返回一个Match对象,否则返回None;
    • re模块的匹配过程:正则表达式文本----编译----->正则表达式对象----匹配---->待匹配文本---->匹配结果。
    • patternr =re.compile(r‘正则表达式’) ----------编译 
    • math = pattern.match('待匹配字符串') ----------匹配
    • print match.group()                             ----------结果

    re.compile(strPattern[, flag]):

    这个方法是Pattern类的工厂方法,用于将字符串形式的正则表达式编译为Pattern对象。 第二个参数flag是匹配模式,取值可以使用按位或运算符'|'表示同时生效,比如re.I | re.M。另外,你也可以在regex字符串中指定模式,比如re.compile('pattern', re.I | re.M)与re.compile('(?im)pattern')是等价的。 
    可选值有:

    • re.I(re.IGNORECASE): 忽略大小写
    • re.M(MULTILINE): 多行模式,改变'^'和'$'的行为
    • re.S(DOTALL): 点任意匹配模式,改变'.'的行为
    • re.L(LOCALE): 使预定字符类 w W  B s S 取决于当前区域设定
    • re.U(UNICODE): 使预定字符类 w W  B s S d D 取决于unicode定义的字符属性

    re.X(VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。以下两个正则表达式是等价的:

    re.compile(r"""d +  # the integral part
                           .            # the decimal point
                           d *        # some fractional digits""", re.X)
     re.compile(r"d+.d*") 

    Match

    Match对象是一次匹配的结果,包含了很多关于此次匹配的信息,可以使用Match提供的可读属性或方法来获取这些信息。

    属性:

    • string: 匹配时使用的文本。
    • re: 匹配时使用的Pattern对象。
    • pos: 文本中正则表达式开始搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。
    • endpos: 文本中正则表达式结束搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。
    • lastindex: 最后一个被捕获的分组在文本中的索引。如果没有被捕获的分组,将为None。
    • lastgroup: 最后一个被捕获的分组的别名。如果这个分组没有别名或者没有被捕获的分组,将为None。

    方法:

    • group([group1, …]): 
      获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。
    • groups([default]):
      以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代,默认为None。
    • groupdict([default]): 
      返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内。default含义同上。
    • start([group]):
      返回指定的组截获的子串在string中的起始索引(子串第一个字符的索引)。group默认值为0。
    • end([group]): 
      返回指定的组截获的子串在string中的结束索引(子串最后一个字符的索引+1)。group默认值为0。
    • span([group]): 
      返回(start(group), end(group))。
    • expand(template):
      将匹配到的分组代入template中然后返回。template中可以使用id或g<id>、g<name>引用分组,但不能使用编号0。id与g<id>是等价的;但10将被认为是第10个分组,如果你想表达1之后是字符'0',只能使用g<1>0。
    import re
    m = re.match(r'(w+) (w+)(?P<sign>.*)', 'hello world!')
     
    print "m.string:", m.string
    print "m.re:", m.re
    print "m.pos:", m.pos
    print "m.endpos:", m.endpos
    print "m.lastindex:", m.lastindex
    print "m.lastgroup:", m.lastgroup
     
    print "m.group(1,2):", m.group(1, 2)
    print "m.groups():", m.groups()
    print "m.groupdict():", m.groupdict()
    print "m.start(2):", m.start(2)
    print "m.end(2):", m.end(2)
    print "m.span(2):", m.span(2)
    print r"m.expand(r'2 13'):", m.expand(r'2 13')
     
    ### output ###
    # m.string: hello world!
    # m.re: <_sre.SRE_Pattern object at 0x016E1A38>
    # m.pos: 0
    # m.endpos: 12
    # m.lastindex: 3
    # m.lastgroup: sign
    # m.group(1,2): ('hello', 'world')
    # m.groups(): ('hello', 'world', '!')
    # m.groupdict(): {'sign': '!'}
    # m.start(2): 6
    # m.end(2): 11
    # m.span(2): (6, 11)
    # m.expand(r'2 13'): world hello!

    Pattern

    Pattern对象是一个编译好的正则表达式,通过Pattern提供的一系列方法可以对文本进行匹配查找。Pattern不能直接实例化,必须使用re.compile()进行构造。

    Pattern提供了几个可读属性用于获取表达式的相关信息:

    • pattern: 编译时用的表达式字符串。
    • flags: 编译时用的匹配模式。数字形式。
    • groups: 表达式中分组的数量。
    • groupindex: 以表达式中有别名的组的别名为键、以该组对应的编号为值的字典,没有别名的组不包含在内。
    import re
    p = re.compile(r'(w+) (w+)(?P<sign>.*)', re.DOTALL)
     
    print "p.pattern:", p.pattern
    print "p.flags:", p.flags
    print "p.groups:", p.groups
    print "p.groupindex:", p.groupindex
     
    ### output ###
    # p.pattern: (w+) (w+)(?P<sign>.*)
    # p.flags: 16
    # p.groups: 3
    # p.groupindex: {'sign': 3}

    实例方法

    1、match(string[, pos[, endpos]]) | re.match(pattern, string[, flags])

    这个方法将从string的pos下标处起尝试匹配pattern;如果pattern结束时仍可匹配,则返回一个Match对象;如果匹配过程中pattern无法匹配,或者匹配未结束就已到达endpos,则返回None。 

    >>> import re
    >>> re.match(r'<link rel="(.+)" href="//(.+)" />','<link rel="dns-prefetch" href="//g.alicdn.com" />')
    <_sre.SRE_Match object at 0x0000000002B6FE88>
    >>> re.match(r'<link rel="(.+)" href="//(.+)" />','<link reB="dns-prefetch" href="//g.alicdn.com" />')
    >>>

    2、search(string[, pos[, endpos]]) | re.search(pattern, string[, flags])

    这个方法用于查找字符串中可以匹配成功的子串。从string的pos下标处起尝试匹配pattern,如果pattern结束时仍可匹配,则返回一个Match对象;若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None。 
    pos和endpos的默认值分别为0和len(string));re.search()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。

    # encoding: UTF-8 
    import re 
    pattern = re.compile(r'world') 
    match = pattern.search('hello world!') 
    print match.group() 
     
    ### Output ### 
    # world

    3、split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]): 
    按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割。

    p = re.compile(r'd+')
    print p.split('one1two2three3four4')
     
    ### output ###
    # ['one', 'two', 'three', 'four', ''] 

    4、findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]): 
    搜索string,以列表形式返回全部能匹配的子串。

    p = re.compile(r'd+')
    print p.findall('one1two2three3four4')
     
    ### output ###
    # ['1', '2', '3', '4']

    5、finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]): 
    搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。

    p = re.compile(r'd+')
    for m in p.finditer('one1two2three3four4'):
        print m.group(),
     
    ### output ###
    # 1 2 3 4

    6、sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]): 
    使用repl替换string中每一个匹配的子串后返回替换后的字符串。 
    当repl是一个字符串时,可以使用id或g<id>、g<name>引用分组,但不能使用编号0。 
    当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。 
    count用于指定最多替换次数,不指定时全部替换。 

    p = re.compile(r'(w+) (w+)')
    s = 'i say, hello world!'
     
    print p.sub(r'2 1', s)
     
    def func(m):
        return m.group(1).title() + ' ' + m.group(2).title()
     
    print p.sub(func, s)#此处函数func内传入的参数为re.match的返回值
    #print func(re.match(p,s)) 的输出为I Say
    #可见此处函数(sub)的执行特点相当于执行了两次re.match
    ###output ### # say i, world hello! # I Say, Hello World!

    7、subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]): 
    返回 (sub(repl, string[, count]), 替换次数)。

    p = re.compile(r'(w+) (w+)')
    s = 'i say, hello world!'
     
    print p.subn(r'2 1', s)
     
    def func(m):
        return m.group(1).title() + ' ' + m.group(2).title()
     
    print p.subn(func, s)
     
    ### output ###
    # ('say i, world hello!', 2)
    # ('I Say, Hello World!', 2)

    8、爬虫常用的几个函数

    def getHtml(url):
        page = urllib.urlopen(url)
        html  =page.read()
        return html
    def GetLink(html):  
    #    reg = r'<link rel="(.+)" href="//(.+)" />'#正则表达式模板
        imgre = re.compile(reg)  
        imglist = re.findall(imgre,html)  
        return imglist  

     参考:http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html

  • 相关阅读:
    FreeMarker MyEclipse IDE
    Mybatis MapperScannerConfigurer 自动扫描 将Mapper接口生成代理注入到Spring
    Mybatis SqlSessionTemplate 源码解析
    Mybatis Interceptor 拦截器原理 源码分析
    MyBatis Mapper 接口如何通过JDK动态代理来包装SqlSession 源码分析
    MyEclipse SVN 下面切换用户的解决方案
    SpringMVC 多个数据源 配置多个事物管理器 Multiple Transaction Managers
    Activiti 获取定义
    [No000066]python各种类型转换-int,str,char,float,ord,hex,oct等
    [No000065]python 获取当前时间
  • 原文地址:https://www.cnblogs.com/w-smile/p/7203502.html
Copyright © 2020-2023  润新知