zoukankan      html  css  js  c++  java
  • Python 模块学习:re模块

    今天学习了Python中有关正则表达式的知识。关于正则表达式的语法,不作过多解释,网上有许多学习的资料。这里主要介绍Python中常用的正则表达式处理函数。

    方法/属性 作用
    match() 决定 RE 是否在字符串刚开始的位置匹配
    search() 扫描字符串,找到这个 RE 匹配的位置
    findall() 找到 RE 匹配的所有子串,并把它们作为一个列表返回
    finditer() 找到 RE 匹配的所有子串,并把它们作为一个迭代器返回

    match() 函数只检查 RE 是否在字符串开始处匹配,而 search() 则是扫描整个字符串。

    match() 只报告一次成功的匹配,它将从 0 处开始;如果匹配不是从 0 开始的,match() 将不会报告它。

    search() 将扫描整个字符串,并报告它找到的第一个匹配。


    match()、seerch()、finditer()如果匹配成功则返回一个Match Object对象,该对象有以下属性、方法:

    方法/属性 作用
    group() 返回被 RE 匹配的字符串
    start() 返回匹配开始的位置
    end() 返回匹配结束的位置
    span() 返回一个元组包含匹配 (开始,结束) 的位置

    group() 返回re整体匹配的字符串,可以一次输入多个组号,对应组号匹配的字符串。

    1. group()返回re整体匹配的字符串,

    2. group (n,m) 返回组号为n,m所匹配的字符串,如果组号不存在,则返回indexError异常

    #!python
    >>> p = re.compile('(a(b)c)d')
    >>> m = p.match('abcd')
    >>> m.group(0)
    'abcd'
    >>> m.group(1)
    'abc'
    >>> m.group(2)
    'b'

    groups() 方法返回一个包含正则表达式中所有小组字符串的元组,从 1 到 所含的小组号,通常groups()不需要参数,返回一个元组,元组中的元就是正则表达式中定义的组。
    #!python
    >>> p = re.compile('(a(b)c)d')
    >>> m = p.match('abcd')
    >>> m.groups()
    ('abc', 'b')

    使用索引取得相应的组内容,例如:m.groups()[0]

    p2=re.compile(r'''(d)+w''',re.X)  

    >>> p2.match('123a b12123c').group()   # re正则表达式 '(d)+w匹配的字符串

    '123a'

    >>> p2.match('123a b12123c').group(0)

    '123a'

    >>> p2.match('123a b12123c').group(1)  #返回正则表达式中第一个小组即(d)所匹配的字符串

    '3'

    >>> p2.match('123a b12 123c').groups() 
    ('3',)

    re.match ,从字符串开头匹配,返回一个Match Object,或None

      re.match 尝试从字符串的开始匹配一个模式,如:下面的例子匹配第一个单词。

    复制代码
    import re
    text = "JGood is a handsome boy, he is cool, clever, and so on..."
    m = re.match(r"(w+)s", text)
    if m:
    print m.group(0), '
    ', m.group(1)
    else:
    print 'not match'  
    复制代码

    re.match的函数原型为:re.match(pattern, string, flags)

    第一个参数是正则表达式,这里为"(w+)s",如果匹配成功,则返回一个Match,否则返回一个None;

    第二个参数表示要匹配的字符串;

    第三个参数是标致位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。

    方法/属性 作用
    group() 返回被 RE 匹配的字符串
    start() 返回匹配开始的位置
    end() 返回匹配结束的位置
    span() 返回一个元组包含匹配 (开始,结束) 的位置

    re.search  在字符串内查找匹配,找到第一个匹配,返回Match Object,或None

      re.search函数会在字符串内查找模式匹配,直到找到第一个匹配然后返回,如果字符串没有匹配,则返回None。

    复制代码
    import re
    text = "JGood is a handsome boy, he is cool, clever, and so on..."
    m = re.search(r'shan(ds)omes', text)
    if m:
    print m.group(0), m.group(1)
    else:
    print 'not search'  
    复制代码

    re.search的函数原型为: re.search(pattern, string, flags)

    每个参数的含意与re.match一样。 

    re.match与re.search的区别:re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

    re.sub   替换所有的匹配项,返回一个替换后的字符串,如果匹配失败,返回原字符串

      re.sub用于替换字符串中的匹配项。下面一个例子将字符串中的空格 ' ' 替换成 '-' : 

    import re
    text = "JGood is a handsome boy, he is cool, clever, and so on..."
    print re.sub(r's+', '-', text) 

     re.sub的函数原型为:re.sub(pattern, repl, string, count)

    其中第二个函数是替换后的字符串;本例中为'-'

    第四个参数指替换个数。默认为0,表示每个匹配项都替换。

    re.sub还允许使用函数对匹配项的替换进行复杂的处理。如:re.sub(r's', lambda m: '[' + m.group(0) + ']', text, 0);将字符串中的空格' '替换为'[ ]'。

    sub() 方法提供一个替换值,可以是字符串或一个函数,和一个要被处理的字符串

    当使用模块级的 re.sub() 函数时,模式作为第一个参数。模式也许是一个字符串或一个 `RegexObject`;如果你需要指定正则表达式标志,你必须要么使用 `RegexObject` 做第一个参数,或用使用模式内嵌修正器,如 sub("(?i)b+", "x", "bbbb BBBB") returns 'x x'。 

    import re

    def hexrepl( match ):
         "Return the hex string for a decimal number"
         value = int( match.group() )
         return hex(value)

    p = re.compile(r'd+')

    print p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
    #Call 0xffd2 for printing, 0xc000 for user code.


    import re

    text = "JGood is a handsome boy, he is cool, clever, and so on..."

    print re.sub(r's+', '-', text)
    #JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...

    print re.sub(r's', lambda m: '[' + m.group(0) + ']', text)
    #JGood[ ]is[ ]a[ ]handsome[ ]boy,[ ]he[ ]is[ ]cool,[ ]clever,[ ]and[ ]so[ ]on...

    print re.sub(r'a', lambda m: '[' + m.group(0) + ']', text) #在a的两边加[ ],也可以用string.replace()

    #JGood is [a] h[a]ndsome boy, he is cool, clever, [a]nd so on...

    subn ( )  与 sub( ) 相同,但返回新的字符串和替换次数

    print re.subn('i','I','Paris in the the spring')  # ('ParIs In the the sprIng', 3)

    空匹配只有在它们没有紧挨着前一个匹配时才会被替换掉。

    #!python

    >>> p = re.compile('x*')

    >>> p.sub('-', 'abxd')

    '-a-b-d-'

    re.split     以列表形式返回分割的字符串

      可以使用re.split来分割字符串,如:re.split(r's+', text);将字符串按空格分割成一个单词列表。

         

    split(string [, maxsplit = 0])

    你可以通过设置 maxsplit 值来限制分片数。当 maxsplit 非零时,最多只能有 maxsplit 个分片,字符串的其余部分被做为列表的最后部分返回。在下面的例子中,定界符可以是非数字字母字符的任意序列。

    #!python
    >>> p = re.compile(r'W+')
    >>> p.split('This is a test, short and sweet, of split().')
    ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
    >>> p.split('This is a test, short and sweet, of split().', 3)
    ['This', 'is', 'a', 'test, short and sweet, of split().']

    有时,你不仅对定界符之间的文本感兴趣,也需要知道定界符是什么。定界符可以是非数字字母字符的任意序列 ,如果捕获括号在 RE中使用,那么它们(定界符)的值也会当作列表的一部分返回。比较下面的调用:

    re.split("([ab])","carbs")  #   ['c', 'a', 'r', 'b', 's']     定界符是a或b,结果返回界定符a、b。

    re.split("([ab]#)", "carbs")  #  ['carbs']   定界符是a#或b#,结果 ['carbs'] 


    #!python
    >>> p = re.compile(r'W+')
    >>> p2 = re.compile(r'(W+)')
    >>> p.split('This... is a test.')
    ['This', 'is', 'a', 'test', '']
    >>> p2.split('This... is a test.')
    ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']

    re.findall  以列表形式返回所有匹配的字符串

      re.findall可以获取字符串中所有匹配的字符串。如:re.findall(r'w*oow*', text);获取字符串中,包含'oo'的所有单词。

          

             (pattern) 匹配 pattern并获取这一匹配


           import re

           text = "JGood is a  handsome boy,he is handsome and cool,clever,and so on ...."


            print re.findall(r'w*oow*',text) #结果:['JGood', 'cool']

           print re.findall(r'(w)*oo(w)*',text) # ()表示子表达式 结果:[('G', 'd'), ('c', 'l')]

    在 Python 2.2中,也可以用 finditer() 方法。

    #!python
    >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
    >>> iterator
    <callable-iterator object at 0x401833ac>
    >>> for match in iterator:
    ...     print match.group() , match.span()
    ...     
    12 (0, 2)
    11 (22, 24)
    10 (29, 31)
    


    re.compile

      可以把正则表达式编译成一个正则表达式对象。可以把那些经常使用的正则表达式编译成正则表达式对象,这样可以提高一定的效率。下面是一个正则表达式对象的一个例子:

    import re
    text = "JGood is a handsome boy, he is cool, clever, and so on..."
    regex = re.compile(r'w*oow*')
    print regex.findall(text)   #查找所有包含'oo'的单词
    print regex.sub(lambda m: '[' + m.group(0) + ']', text) #将字符串中含有'oo'的单词用[]括起来。

    转自:http://www.python8.org/a/fenleiwenzhang/yuyanjichu/2009/0901/150.html

     
    0
  • 相关阅读:
    addEventListener、onclick和jquery的bind()、click()
    JQuery的click、bind、delegate、off、unbind
    JS的Scope
    JS对象深入剖析
    IP查找所属网段
    C#类的成员初始化顺序
    C#操作XML的完整例子——XmlDocument篇
    【开发实例】C#调用SAPI实现语音合成的两种方法
    C#打包制作安装程序过程全记录
    C# 仿制QQ弹出新闻消息框
  • 原文地址:https://www.cnblogs.com/jiangzhaowei/p/5738590.html
Copyright © 2011-2022 走看看