码迷,mamicode.com
首页 > 编程语言 > 详细

python正则表达式

时间:2016-06-30 11:00:47      阅读:346      评论:0      收藏:0      [点我收藏+]

标签:

五、python正则表达式

标签: python 正则表达式


1. 正则表达式的使用

    1. >>> p = re.compile("abc")
    2. >>> m= p.match("abcdf")
    3. >>> type(m)
    4. <type _sre.SRE_Match>
    5. >>> print m.group()
    6. abc
    7. >>> m= p.match("acbcdf")
    8. >>> print m.group()
    9. Traceback (most recent call last):
    10. File "<stdin>", line 1, in <module>
    11. AttributeError: NoneType object has no attribute group
    12. >>> type(m) #无匹配模式打印m为NoneType值
    13. <type NoneType>

2. re.compile()

3. 正则表达式介绍

元字符

. 除换行符的任意字符 DOTALL 
\ 转义字符 
[…] 字符集合 
\d 数字:[0-9] 
\D 非数字[^0-9] 
\s 空白字符[<空格>\t\r\n\f\n] 
\S 非空白字符[^\s] 
\w 单词字符[A-Za-z0-9_] 
\W 非单词字符[^\w]

    1. >>> p = re.compile(".")
    2. >>> m1 = p.match(dfg)
    3. >>> print m1.group()
    4. d
    5. >>> m1 = p.match(\n)
    6. >>> print m1.group()
    7. Traceback (most recent call last):
    8. File "<stdin>", line 1, in <module>
    9. AttributeError: NoneType object has no attribute group
    10. >>> p = re.compile("\.")
    11. >>> m2 = p.match(abc.ef)
    12. >>> print m2.group()
    13. Traceback (most recent call last):
    14. File "<stdin>", line 1, in <module>
    15. AttributeError: NoneType object has no attribute group
    16. >>> m2 = p.match(‘.‘)
    17. >>> print m2.group()
    18. .
    19. >>> p = re.compile("\.")
    20. >>> m = p.findall("abc.ef.gh") #findall查找所有
    21. >>> print m
    22. [‘.‘, ‘.‘]
    23. >>> p = re.compile(‘[abc]‘) #子集
    24. >>> m= p.findall(abcdef)
    25. >>> print m
    26. [a, b, c]
    27. >>> m1 = p.match(abcdef)
    28. >>> print m1.group()
    29. a

数量词

* 匹配前一个字符0或者多次
+ 匹配前一个字符1次或者多次
? 匹配前一个字符0次或者1次
{m} 匹配前一个字符m次
{m,n} 匹配前一个字符m至n次
数量词? 变成非贪婪模式
    1. >>> p = re.compile(‘[abc]*‘)
    2. >>> print p.findall(abcdef)
    3. [abc, ‘‘, ‘‘, ‘‘, ‘‘]
    4. >>> p = re.compile(‘[abc]+‘)
    5. >>> print p.findall(abcdef)
    6. [abc]
    7. >>> p = re.compile(‘[abc]*?‘) #非贪婪模式
    8. >>> print p.findall(abcdef)
    9. [‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘]
    10. >>> p = re.compile(‘[abc]+?‘)
    11. >>> print p.findall(abcdef)
    12. [a, b, c]
    13. >>> p = re.compile(‘[abc]{2}‘)
    14. >>> print p.findall(abcdef)
    15. [ab]
    16. >>> print p.findall(ababab)
    17. [ab, ab, ab]
    18. >>> p = re.compile(‘[abc]{2,3}‘)
    19. >>> print p.findall(abcabc)
    20. [abc, abc]
    21. >>> p = re.compile(‘[abc]{2,3}?‘) #非贪婪模式
    22. >>> print p.findall(abcabc)
    23. [ab, ca, bc]
    24. >>>

边界符 
^ 匹配字符串开头,多行匹配每一行开头 
$ 匹配字符串末尾,多行匹配每一行末尾 
\A 仅匹配字符串开头 
\Z 仅匹配字符串末尾 
\b 匹配\w 和 \W 之间

    1. >>> p=re.compile(‘^[abc]*‘)
    2. >>> p.findall("abcdef")
    3. [abc]
    4. >>> p.findall("bcdef")
    5. [bc]
    6. >>> p.findall("def")
    7. [‘‘]
    8. >>> p.findall("defabc")
    9. [‘‘]
    10. >>> p=re.compile(‘[abc]*‘)
    11. >>> p.findall("defabc")
    12. [‘‘, ‘‘, ‘‘, abc, ‘‘]
    13. >>> p=re.compile(‘[^abc]*‘) #^边界符放在[]内表示非abc字符的查找
    14. >>> p.findall("defabc")
    15. [def, ‘‘, ‘‘, ‘‘, ‘‘]
    16. >>> p=re.compile(‘^[abc]*e$)
    17. >>> p.findall("defabc")
    18. []
    19. >>> p.findall("abcde")
    20. []
    21. >>> p.findall("abce")
    22. [abce]
    23. >>> p.findall("bce")
    24. [bce]
    25. >>> p.findall("ce")
    26. [ce]
    27. >>> p=re.compile(‘^[abc]*?e$)
    28. >>> p.findall("abce")
    29. [abce]

逻辑 分组

|       左右表达式任意匹配一个
    先匹配左边一旦成功则跳过匹配右边
    如果|没有包含在()中,匹配整个正则表达式
(…)     分组匹配,从左到右,每遇到一个 ( 编号+1 
    分组后面可加数量词
(?P<name>…) 除了分组序号外,指定一个 name的别名
\<number> 引用编号为<number>的分组匹配到的字符串
(?P=name) 引用别名为<name>的分组匹配到的串
    1. >>> p=re.compile(abc)
    2. >>> m =p.match(abcdef)
    3. >>> print m.group()
    4. abc
    5. >>> dir(m)
    6. [__class__, __copy__, __deepcopy__, __delattr__, __doc__, __format__, __getattribute__, __hash__, __init__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__, end, endpos, expand, group, groupdict, groups, lastgroup, lastindex, pos, re, regs, span, start, string]
    7. >>> type(m.groups())
    8. <type tuple>
    9. >>> m.groupdict()
    10. {}
    11. >>> p=re.compile(‘(a)(b)(c)‘)
    12. >>> m =p.match(abcdef)
    13. >>> m.group()
    14. abc
    15. >>> m.groups()
    16. (a, b, c)
    17. >>> m =p.match(abdef)
    18. >>> m.groups()
    19. Traceback (most recent call last):
    20. File "<stdin>", line 1, in <module>
    21. AttributeError: NoneType object has no attribute groups
    22. >>> m =p.match(abcdef)
    23. >>> m.groups()
    24. (a, b, c)
    25. >>> m.groupdict()
    26. {}
    27. >>> p=re.compile(‘(a)b(c)‘)
    28. >>> m =p.match(abcdef)
    29. >>> m.groups()
    30. (a, c)
    31. >>> m =p.match(adcdef)
    32. >>> m.groups()
    33. Traceback (most recent call last):
    34. File "<stdin>", line 1, in <module>
    35. >>> p=re.compile(‘(?P<name>a)b(c)‘) #命名分组与匿名分组混合使用
    36. >>> m=p.match(abcdef)
    37. >>> m.groups()
    38. (a, c)
    39. >>> m.groupdict()
    40. {name: a}
    41. >>> m.group()
    42. abc
    43. >>> p=re.compile(‘(?P<name>a)b(c)(?P=name)‘)
    44. >>> p.findall(abcd)
    45. []
    46. >>> p.findall(abca)
    47. [(a, c)]
    48. >>> p.findall(abcaa)
    49. [(a, c)]
    50. >>> p=re.compile(‘(?P<name>a)b(c)(?P=name)\1)
    51. >>> p.findall(abcaa)
    52. []
    53. >>> p=re.compile(r‘(?P<name>a)b(c)(?P=name)\1) #防止上句\1变成转义字符,r为原生字符。\1为编号的索引位置
    54. >>> p.findall(abcaa)
    55. [(a, c)]
    56. >>> p.findall(abcac)
    57. []
    58. >>> p=re.compile(r‘(?P<name>a)b(c)(?P=name)\2)
    59. >>> p.findall(abcac)
    60. [(a, c)]
    61. >>> m =p.match(abcac)
    62. >>> m.group()
    63. abcac
    64. >>> m.groups()
    65. (a, c)
    66. >>> m.groupdict()
    67. {name: a}
    68. >>> m.group(2)
    69. c

特殊构造

(?:…) (…)不分组版本,用于使用 | 或者后接数量词
(?iLmsux) iLmsux的每个字符代表一个匹配模式,只能用在正
则表达式的开头,可选多个
(?#...) #号后的内容将作为注释
(?=…) 之后的字符串内容需要匹配表达式才能成功匹配
(?!...) 之后的字符串不匹配表达式才能成功
(?<=…) 之前的字符串需要匹配表达式才能成功
(?<!...) 之前的字符串需要不匹配表达式才能成功
(?(id/name) yes |no)        如果编号为id/名字为name的组匹配到字符串,则需
要匹配yes,否则匹配no,no可以省略
    1. >>> p=re.compile(r‘(?:abc){2}‘) #不分组模式
    2. >>> p.findall(abc)
    3. []
    4. >>> p.findall(abcabc)
    5. [abcabc]
    6. >>> p.findall(abcabcdef)
    7. [abcabc]
    8. >>> m=p.match("abcabc")
    9. >>> m.groups() #不是分组,只是格式串
    10. ()
    11. >>> p=re.compile(ra(?=\d)‘)
    12. >>> p.findall(a1a2a3)
    13. [a, a, a]
    14. >>> p=re.compile(r\w(?=\d)‘)
    15. >>> p.findall(word1 wor2 wo3)
    16. [d, r, o]
    17. >>> p=re.compile(r\w+(?=\d)‘)
    18. >>> p.findall(word1 wor2 wo3)
    19. [word, wor, wo]
    20. >>> p=re.compile(r\w+?(?=\d)‘) #非贪婪模式
    21. >>> p.findall(word1 wor2 wo3)
    22. [word, wor, wo]
    23. >>> p=re.compile(ra(?!\d)‘) #不匹配表达式
    24. >>> p.findall(word1 wor2 wo3)
    25. []
    26. >>> p.findall(word1 wor2 awo3)
    27. [a]
    28. >>> p=re.compile(r‘(?<=\d)a)
    29. >>> p.findall(word1 wor2 awo3)
    30. []
    31. >>> p.findall(word1 wor2 awo3a)
    32. [a]
    33. >>> p=re.compile(r‘(?<!\d)a)
    34. >>> p.findall(word1 wora2 awo3a)
    35. [a, a]
    36. >>> p=re.compile(r‘(\d)?abc(?(1)\b|abc)‘) #逻辑匹配
    37. >>> p.findall(1abc4)
    38. []
    39. >>> p.findall(1abcabc)
    40. [‘‘]
    41. >>> p.findall(abcabc)
    42. [‘‘]
    43. >>> m=p.match (abcabc)
    44. >>> m.group()
    45. abcabc

iLmsux 正则表达式使用开关

I re.I 忽略大小写
L re.L 使用预定字符类 \w \W \b \B \s \S 取决当前区域设定
m re.M 多行模式改变^ 和 $ 的行为
s re.S  . 任意匹配模式
u re.U 使用预定字符类 \w \W \b \B \s \S \d \D 取决unicode定义的字符属性
x re.X 详细模式,可以多行,忽略空白字符,并且可以加入注释
    1. >>>
    2. >>> p=re.compile(r‘(?i)abc)
    3. >>> p.findall(abcabc)
    4. [abc, abc]
    5. >>> p.findall(Abcabc)
    6. [Abc, abc]
    7. >>> p=re.compile(rabc,re.I) #常见用法,忽略大小写
    8. >>> p.findall(Abcabc)
    9. [Abc, abc]

4. 贪婪模式和非贪婪模式

正则表达式通常用于在文本中查找匹配的字符串。Python
里数量词默认是贪婪的(在少数语言里也可能是默认非贪
婪),总是尝试匹配尽可能多的字符;非贪婪的则相反,
总是尝试匹配尽可能少的字符。例如:正则表达式"ab*"如
果用于查找"abbbc",将找到"abbb"。而如果使用非贪婪
的数量词"ab*?",将找到"a"。

5. re模块的其他工具

  • re.compile(strPattern[, flag]) #函数返回pattern模式对象
  • pattern
  • match 返回查找的结果对象,从文本开头,只要匹配就返回
  • search 返回查找的结果对象,在整个目标文本内查找
    1. >>> m=p.match(cdabcaaa)
    2. >>> m.group()
    3. Traceback (most recent call last):
    4. File "<stdin>", line 1, in <module>
    5. AttributeError: NoneType object has no attribute group
    6. >>> m=p.search(cdabcaaa)
    7. >>> m.group()
    8. abc
  • split 字符串分拆
  • findall 查找目标串中所有满足条件的pattern的字符串,返回一个列表
  • finditer 返回一个生成器
    1. >>> p=re.compile(a)
    2. >>> m=p.finditer(abcaaadefaa)
    3. >>> type(m)
    4. <type callable-iterator>
    5. >>> m.next()
    6. <_sre.SRE_Match object at 0x7fc971e3a5e0>
    7. >>> dir(m.next())
    8. [__class__, __copy__, __deepcopy__, __delattr__, __doc__, __format__, __getattribute__, __hash__, __init__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__, end, endpos, expand, group, groupdict, groups, lastgroup, lastindex, pos, re, regs, span, start, string]
    9. >>> m.next().group()
    10. a
    11. >>> m.next().group()
    12. a
    13. >>> m.next().group()
    14. a
    15. >>> m.next().group()
    16. Traceback (most recent call last):
    17. File "<stdin>", line 1, in <module>
    18. StopIteration
  • sub 根据模式串进行编译和交互的函数
    1. >>> import re
    2. >>> p=re.compile(r‘(\w+) (\w+)‘) #使用效果函数进行位置替换
    3. >>> s=hi you ,good boy
    4. >>> print p.sub(r\2 \1,s)
    5. you hi ,boy good

python正则表达式

标签:

原文地址:http://blog.csdn.net/refuil/article/details/51787334

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!