1、查找文本中的模式

search()函数取模式和要扫描的文本作为输入,找到这个模式时就返回一个match对象。如果没有找到模式,search()就返回None。

每个match对象包含有关匹配性质的信息,包含原输入字符串,所使用的正则表达式以及模式在原字符串出现的位置。

  1. import re
  2. pattern = 'this'
  3. text = 'Does this text match the pattern?'
  4. match = re.search(pattern, text)
  5. s = match.start()
  6. e = match.end()
  7. print('Found "{}"\nin "{}"\nfrom {} to ("{}")'.format(match.re.pattern, match.string, s, e, text[s:e]))
  8. _____________________输出___________________________________________
  9. Found "this"
  10. in "Does this text match the pattern?"
  11. from 5 to ("9")

start()和end()方法可以提供字符串中的相应索引,指示与模式匹配的文本在字符串中出现的位置。

2、编译表达式

尽管re包括模块级函数,可以处理作为文本字符串的正则表达式,但是对于程序频繁使用的表达式而言,编译它们会更为高效。compile()函数会把一个表达式字符串转换为一个Regex0bject。

  1. import re
  2. regexes = [
  3. re.compile(p)
  4. for p in ['this', 'that']
  5. ]
  6. text = 'Does this text match the pattern?'
  7. print('Text: {!r}\n'.format(text))
  8. for regex in regexes:
  9. print('Seeking "{}" ->'.format(regex.pattern),end=' ')
  10. if regex.search(text):
  11. print('match')
  12. else:
  13. print('no match')
  14. _________________________输出_________________________________
  15. Text: 'Does this text match the pattern?'
  16. Seeking "this" -> match
  17. Seeking "that" -> no match

模块级函数会维护一个包含已编译表达式的缓存,不过这个缓存的大小是有限的,另外直接使用已编译表达式可以避免与缓存查找相关的开销。使用已编译表达式的另一个好处为,通过在加载模块时预编译所有的表达式,可以把编译工作转移到应用开始时,而不是当程序响应一个用户动作时才编译。

3、多重匹配

使用search()来查找字面量文本字符串的单个实例,findall()函数会返回输入中与模式匹配而且不重叠的所有子串。

  1. import re
  2. text = 'abbaaabbbbaaaaaa'
  3. pattern = 'ab'
  4. for match in re.findall(pattern, text):
  5. print('Found {!r}'.format(match))
  6. _______________________输出_____________________
  7. Found 'ab'
  8. Found 'ab'

finditer()返回一个迭代器,它会生成Match实例,而不是像findall()那样返回字符串。

  1. import re
  2. text = 'abbaaabbbbaaaaaa'
  3. pattern = 'ab'
  4. for match in re.finditer(pattern, text):
  5. s = match.start()
  6. e = match.end()
  7. print('Found {!r} at {:d}:{:d}'.format(text[s:e],s,e))
  8. _______________________输出_______________________________
  9. Found 'ab' at 0:2
  10. Found 'ab' at 5:7

4、模式语法

正则表达式还支持更加强大的模式。模式可以重复,可以锚定到输入中不同的逻辑位置,可以用紧凑的形式表述而不需要在模式中提取每一个重复的字符

  1. import re
  2. def test_pattern(text,patterns):
  3. for pattern, desc in patterns:
  4. print("'{}' ({})\n".format(pattern,desc))
  5. print(" '{}'".format(text))
  6. for match in re.finditer(pattern, text):
  7. s = match.start()
  8. e = match.end()
  9. substr = text[s:e]
  10. n_backslashes = text[:s].count('\\')
  11. prefix = '.' * (s+n_backslashes)
  12. print(" {}'{}'".format(prefix,substr))
  13. print()
  14. return
  15. if __name__ == "__main__":
  16. test_pattern('abbaaabbbbaaaaaa',[('ab',"'a' follow by 'b'"),])
  17. ________________________输出_______________________________________
  18. 'ab' ('a' follow by 'b')
  19. 'abbaaabbbbaaaaaa'
  20. 'ab'
  21. .....'ab'

输出显示输入文本以及输入中与模式匹配的各个部分的子串区间。

重复

模式中有5种表示重复的方法。模式后面如果有元字符*,则表示重复0次或多次(允许一个模式重复0次是指这个模式即使不出现也可以匹配)。如果把*替换为+,那么模式必须至少出现一次才能匹配。使用?表示模式出现0次或1次。如果要制定出现次数,需要在模式后面使用{m},m表示模式应重复的次数。最后,如果要允许一个可变但有限的重复次数,那么可以使用{m,n},这里m是最少重复次数,n是最大重复次数。如果省略n({m,}),则表示值必须至少出现m次,但没有最大限制。

  1. test_pattern('abbaabbba',[('ab*','a followed by zero or more b'),
  2. ('ab+','a followed by one or more b'),
  3. ('ab?','a followed by zero or one b'),
  4. ('ab{3}','a followed by three b'),
  5. ('ab{2,3}','a followed by two or three b')],
  6. )
  7. __________________________输出__________________________________
  8. 'ab*' (a followed by zero or more b)
  9. 'abbaabbba'
  10. 'abb'
  11. ...'a'
  12. ....'abbb'
  13. ........'a'
  14. 'ab+' (a followed by one or more b)
  15. 'abbaabbba'
  16. 'abb'
  17. ....'abbb'
  18. 'ab?' (a followed by zero or one b)
  19. 'abbaabbba'
  20. 'ab'
  21. ...'a'
  22. ....'ab'
  23. ........'a'
  24. 'ab{3}' (a followed by three b)
  25. 'abbaabbba'
  26. ....'abbb'
  27. 'ab{2,3}' (a followed by two or three b)
  28. 'abbaabbba'
  29. 'abb'
  30. ....'abbb'

处理重复指令时,re在匹配模式时通常会尽可能多地消费输入。这种像“贪心”的行为可能会导致单个匹配减少,或匹配结果包含比预想更多的输入文本。可以在重复指令后面加?来关闭贪心行为。

  1. test_pattern('abbaabbba',[('ab*?','a followed by zero or more b'),
  2. ('ab+?','a followed by one or more b'),
  3. ('ab??','a followed by zero or one b'),
  4. ('ab{3}?','a followed by three b'),
  5. ('ab{2,3}?','a followed by two or three b')],
  6. )
  7. ______________________________输出________________________________
  8. 'ab*?' (a followed by zero or more b)
  9. 'abbaabbba'
  10. 'a'
  11. ...'a'
  12. ....'a'
  13. ........'a'
  14. 'ab+?' (a followed by one or more b)
  15. 'abbaabbba'
  16. 'ab'
  17. ....'ab'
  18. 'ab??' (a followed by zero or one b)
  19. 'abbaabbba'
  20. 'a'
  21. ...'a'
  22. ....'a'
  23. ........'a'
  24. 'ab{3}?' (a followed by three b)
  25. 'abbaabbba'
  26. ....'abbb'
  27. 'ab{2,3}?' (a followed by two or three b)
  28. 'abbaabbba'
  29. 'abb'
  30. ....'abb'

字符集

字符集是一组字符,包含可以与模式中当前位置匹配的所有字符。例如,[a,b]可以匹配为a或b

  1. test_pattern('abbaabbba',[('[ab]','either a or b'),
  2. ('a[ab]+','a followed by one or more a or b'),
  3. ('a[ab]+?','a followed by one or more a or b, not greedy')],
  4. )
  5. ________________________________输出__________________________________________
  6. '[ab]' (either a or b)
  7. 'abbaabbba'
  8. 'a'
  9. .'b'
  10. ..'b'
  11. ...'a'
  12. ....'a'
  13. .....'b'
  14. ......'b'
  15. .......'b'
  16. ........'a'
  17. 'a[ab]+' (a followed by one or more a or b)
  18. 'abbaabbba'
  19. 'abbaabbba'
  20. 'a[ab]+?' (a followed by one or more a or b, not greedy)
  21. 'abbaabbba'
  22. 'ab'
  23. ...'aa'

尖字符(^)代表要查找不在这个尖字符后面的集合中的字符

  1. test_pattern('This is some text -- with punctuation',[('[^-. ]+','sequences without -, ., or space')],)
  2. __________________________________输出__________________________________
  3. '[^-. ]+' (sequences without -, ., or space)
  4. 'This is some text -- with punctuation'
  5. 'This'
  6. .....'is'
  7. ........'some'
  8. .............'text'
  9. .....................'with'
  10. ..........................'punctuation'

利用字符区间来定义一个字符集

  1. test_pattern('This is some text -- with punctuation',
  2. [('[a-z]+','sequences of lowercase letters'),
  3. ('[A-Z]+','sequences of uppercase letters'),
  4. ('[a-zA-Z]+','sequences of lower- or uppercase letters'),
  5. ('[a-z][A-Z]+','one uppercase followed by lowercase')],
  6. )
  7. ————————————————————————————————————输出————————————————————————————————————
  8. '[a-z]+' (sequences of lowercase letters)
  9. 'This is some text -- with punctuation'
  10. .'his'
  11. .....'is'
  12. ........'some'
  13. .............'text'
  14. .....................'with'
  15. ..........................'punctuation'
  16. '[A-Z]+' (sequences of uppercase letters)
  17. 'This is some text -- with punctuation'
  18. 'T'
  19. '[a-zA-Z]+' (sequencesof lower- or uppercase letters)
  20. 'This is some text -- with punctuation'
  21. 'This'
  22. .....'is'
  23. ........'some'
  24. .............'text'
  25. .....................'with'
  26. ..........................'punctuation'
  27. '[a-z][A-Z]+' (one uppercase followed by lowercase)
  28. 'This is some text -- with punctuation'

元字符点号(.)指示模式应当匹配该位置的单个字符

  1. test_pattern('This is some text -- with punctuation',
  2. [('a.','a followed by any one character'),
  3. ('b.','b follwed by any one character'),
  4. ('a.*b','a followed by anything ending in b'),
  5. ('a.*?b','a followed by anything, ending in b')],
  6. )
  7. ____________________________输出_____________________________________
  8. 'a.' (a followed by any one character)
  9. 'This is some text -- with punctuation'
  10. ................................'at'
  11. 'b.' (b follwed by any one character)
  12. 'This is some text -- with punctuation'
  13. 'a.*b' (a followed by anything ending in b)
  14. 'This is some text -- with punctuation'
  15. 'a.*?b' (a followed by anything, ending in b)
  16. 'This is some text -- with punctuation'

转义码

转义码 含义
\d

数字

\D

非数字

\s 空白符(制表符、空格、换行等)
\S 非空白符
\w

字母数字

\W 非字母数字
  1. test_pattern('A prime #1 example!',
  2. [(r'\d+','sequence of digits'),
  3. (r'\D+','sequence of non-digits'),
  4. (r'\s+','sequence of whitespqce'),
  5. (r'\S+','sequence of non-whitespqce'),
  6. (r'\w+','alphanumeric characters'),
  7. (r'\W+','non-alphanumeric'],
  8. )
  9. ___________________________输出_______________________________
  10. '\d+' (sequence of digits)
  11. 'A prime #1 example!'
  12. .........'1'
  13. '\D+' (sequence of non-digits)
  14. 'A prime #1 example!'
  15. 'A prime #'
  16. ..........' example!'
  17. '\s+' (sequence of whitespqce)
  18. 'A prime #1 example!'
  19. .' '
  20. .......' '
  21. ..........' '
  22. '\S+' (sequence of non-whitespqce)
  23. 'A prime #1 example!'
  24. 'A'
  25. ..'prime'
  26. ........'#1'
  27. ...........'example!'
  28. '\w+' (alphanumeric characters)
  29. 'A prime #1 example!'
  30. 'A'
  31. ..'prime'
  32. .........'1'
  33. ...........'example'
  34. '\W+' (non-alphanumeric)
  35. 'A prime #1 example!'
  36. .' '
  37. .......' #'
  38. ..........' '
  39. ..................'!'

要匹配正则表达式语法中包含的字符,需要转义搜索模式中的字符。

  1. test_pattern(r'\d+ \D+ \s+',[(r'\\.\+','escape code')],)
  2. ________________________输出_____________________________
  3. '\\.\+' (escape code)
  4. '\d+ \D+ \s+'
  5. '\d+'
  6. .....'\D+'
  7. ..........'\s+'

锚定

可以使用锚定指令指定模式在输入文本中的相对位置。

正则表达式锚定码

锚定码 含义
^ 字符串或行开头
$ 字符串或行末尾
\A 字符串开头
\Z 字符串末尾
\b 单词开头或末尾的空串
\B 不在的单词开头或末尾的空串
  1. test_pattern('This is some text -- with punctuation',
  2. [(r'^\w+','word at start of string'),
  3. (r'\A\w+','word at start of string'),
  4. (r'\w+\S*$','word near end of string'),
  5. (r'\w+\S*\Z','word near end of string'),
  6. (r'\bt\w+','t at end of word'),
  7. (r'\Bt\B','not start or end of word')],
  8. )
  9. _____________________________输出__________________________________
  10. '^\w+' (word at start of string)
  11. 'This is some text -- with punctuation'
  12. 'This'
  13. '\A\w+' (word at start of string)
  14. 'This is some text -- with punctuation'
  15. 'This'
  16. '\w+\S*$' (word near end of string)
  17. 'This is some text -- with punctuation'
  18. ..........................'punctuation'
  19. '\w+\S*\Z' (word near end of string)
  20. 'This is some text -- with punctuation'
  21. ..........................'punctuation'
  22. '\bt\w+' (t at end of word)
  23. 'This is some text -- with punctuation'
  24. .............'text'
  25. '\Bt\B' (not start or end of word)
  26. 'This is some text -- with punctuation'
  27. .......................'t'
  28. ..............................'t'
  29. .................................'t'

Python正则表达式的re库一些用法(上)的更多相关文章

  1. python正则表达式与Re库

    正则表达式是用来简洁表达一组字符串的表达式,一行胜千言,有点类似于数列的通项公式. 在python中提供了re库(regular expression)即正则表达式库,内置于python的标准库中,导 ...

  2. 【Python】http.client库的用法

    代码: # http.client测试,该库较底层,不常用 import http.client conn=None try: conn=http.client.HTTPSConnection(&qu ...

  3. Python正则表达式如何进行字符串替换实例

    Python正则表达式如何进行字符串替换实例 Python正则表达式在使用中会经常应用到字符串替换的代码.有很多人都不知道如何解决这个问题,下面的代码就告诉你其实这个问题无比的简单,希望你有所收获. ...

  4. Python正则表达式Regular Expression基本用法

    资料来源:http://blog.csdn.net/whycadi/article/details/2011046   直接从网上资料转载过来,作为自己的参考.这个写的很清楚.先拿来看看. 1.正则表 ...

  5. (转)Python爬虫利器一之Requests库的用法

    官方文档 以下内容大多来自于官方文档,本文进行了一些修改和总结.要了解更多可以参考 官方文档 安装 利用 pip 安装 $ pip install requests 或者利用 easy_install ...

  6. python爬虫---selenium库的用法

    python爬虫---selenium库的用法 selenium是一个自动化测试工具,支持Firefox,Chrome等众多浏览器 在爬虫中的应用主要是用来解决JS渲染的问题. 1.使用前需要安装这个 ...

  7. Python爬虫利器一之Requests库的用法

    前言 之前我们用了 urllib 库,这个作为入门的工具还是不错的,对了解一些爬虫的基本理念,掌握爬虫爬取的流程有所帮助.入门之后,我们就需要学习一些更加高级的内容和工具来方便我们的爬取.那么这一节来 ...

  8. 【归纳】正则表达式及Python中的正则库

    正则表达式 正则表达式30分钟入门教程 runoob正则式教程 正则表达式练习题集(附答案) 元字符\b代表单词的分界处,在英文中指空格,标点符号或换行 例子:\bhi\b可以用来匹配hi这个单词,且 ...

  9. Python爬虫:数据分析小能手:JSON库的用法

    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写. 给大家推荐一个Python交流的q裙,大家在学习遇到了什么问题都可以进群一起交流,大家 ...

随机推荐

  1. 浅谈装饰器(Python)

    先来了解函数和执行函数在python的区别   我再重新定义一个函数,在函数前面加上@set_func 执行结果如下:   函数前面没有加@set_fun 执行结果如下:   是不是可以不修改原来的函 ...

  2. HDU 1542 Atlantis(扫描线)题解

    题意:给n个可能相交的矩形,问你不重复的总面积 思路:扫描线,一边扫一边加. 扫描线:图片来源:理解扫描线 假设我们要算以下四个矩形面积,显然中间深色的是重复的.我们按照x的大小,从左往右扫,然后用线 ...

  3. 解决 scapy “NameError: global name 'wrpcap' is not defined” 错误

    解决 scapy "NameError: global name 'wrpcap' is not defined" 错误 通过 scapy 编写发包脚本时遇到如下错误: Trace ...

  4. 将nginx、mysql、php添加至环境变量

    1.问题描述: 修改完nginx配置后想重启nginx服务,执行nginx -s reload 返回了 -bash: nginx: command not found 2.原因: 没有配置环境变量,找 ...

  5. foreach循环里不能remove/add元素的原理

    foreach循环 ​    foreach循环(Foreach loop)是计算机编程语言中的一种控制流程语句,通常用来循环遍历数组或集合中的元素.Java语言从JDK 1.5.0开始引入forea ...

  6. mint修改host

    sudo xed /etc/hosts # Pycharm 0.0.0.0 account.jetbrains.com0.0.0.0 www.jetbrains.com #sublime text3 ...

  7. [Linux]最新sublime text 3显示图标

    sublime text 3显示图标 执行命令 sudo vim /usr/share/applications/sublime_text_3.desktop 添加相应信息 [Desktop Entr ...

  8. Unity --- 在原目录中,将选中的Texture剥离为rgb和alpha

    using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; us ...

  9. Idea 里明明配置了Tomcat,但是右上角任然没有Tomcat显示

    问题截图如下: 上图明明配置了Tomcat,但是Idea右上角任然是Add Configurations 因为这个问题,困扰了好久.解决方法: 点击Add Configurations   出现如下界 ...

  10. pgRouting新增扩展

    环境依赖:postgresql cgal boost perl 环境变量: boost环境变量 CGAL环境变量 postgresql环境变量 1.新建C++ 空项目 2,添加common引用,更改配 ...