| 代码 | 说明 | 
|---|---|
| . | 匹配除换行符以外的任意字符 | 
| \w | 匹配字母或数字或下划线或汉字 | 
| \s | 匹配任意的空白符 | 
| \d | 匹配数字 | 
| \b | 匹配单词的开始或结束 | 
| ^ | 匹配字符串的开始 | 
| $ | 匹配字符串的结束 | 
| 代码/语法 | 说明 | 
|---|---|
| * | 重复零次或更多次 | 
| + | 重复一次或更多次 | 
| ? | 重复零次或一次 | 
| {n} | 重复n次 | 
| {n,} | 重复n次或更多次 | 
| {n,m} | 重复n到m次 | 
| 代码/语法 | 说明 | 
|---|---|
| \W | 匹配任意不是字母,数字,下划线,汉字的字符 | 
| \S | 匹配任意不是空白符的字符 | 
| \D | 匹配任意非数字的字符 | 
| \B | 匹配不是单词开头或结束的位置 | 
| [^x] | 匹配除了x以外的任意字符 | 
| [^aeiou] | 匹配除了aeiou这几个字母以外的任意字符 | 
| 代码/语法 | 说明 | 
|---|---|
| *? | 重复任意次,但尽可能少重复 | 
| +? | 重复1次或更多次,但尽可能少重复 | 
| ?? | 重复0次或1次,但尽可能少重复 | 
| {n,m}? | 重复n到m次,但尽可能少重复 | 
| {n,}? | 重复n次以上,但尽可能少重复 | 
实例1:.*?的使用详情
import re line = ‘booooooobbbbbby123‘ regex_str = ‘.*?(b.*?b).*‘ match_obj = re.match(regex_str,line) if match_obj: print(match_obj.group(1))
运行结果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py booooooob Process finished with exit code 0
实例2:|和()的使用
import re line = ‘boobby123‘ regex_str = ‘((bobby|boobby)123)‘ match_obj = re.match(regex_str,line) if match_obj: print(match_obj.group(1)) print(match_obj.group(2))
运行结果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py boobby123 boobby Process finished with exit code 0
实例3:提取电话号码([]的使用)
import re line = ‘15868197032fsfs‘ regex_str = ‘(1[34578][0-9]{9})‘ match_obj = re.match(regex_str,line) if match_obj: print(match_obj.group(1))
运行结果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py 15868197032 Process finished with exit code 0
实例4:\s的使用举例
import re line = ‘你 好‘ regex_str = ‘(你\s好)‘ match_obj = re.match(regex_str,line) if match_obj: print(match_obj.group(1))
运行结果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py 你 好 Process finished with exit code 0
实例5:[\u4e00-\u9fa5] 的使用举例
import re line = ‘你好‘ regex_str = ‘([\u4e00-\u9fa5]+)‘ match_obj = re.match(regex_str,line) if match_obj: print(match_obj.group(1))
运行结果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py 你好 Process finished with exit code 0
实例6:举例说明提取多种书写方式的出生年月日
import re line = ‘xxx出生于2001年6月‘ line2 = ‘xxx出生于2001/6/1‘ line3 = ‘xxx出生于2001-6-1‘ line4 = ‘xxx出生于2001-06-01‘ line5 = ‘xxx出生于2001-06‘ regex_str = ‘.*出生于(\d{4}[年/-]\d{1,2}($|[月/-]$|[月/-]\d{1,2}))‘ match_obj = re.match(regex_str,line) match_obj2 = re.match(regex_str,line2) match_obj3 = re.match(regex_str,line3) match_obj4 = re.match(regex_str,line4) match_obj5 = re.match(regex_str,line5) if match_obj: print(match_obj.group(1)) print(match_obj2.group(1)) print(match_obj3.group(1)) print(match_obj4.group(1)) print(match_obj5.group(1))
运行结果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py 2001年6月 2001/6/1 2001-6-1 2001-06-01 2001-06 Process finished with exit code 0
原文:http://www.cnblogs.com/licl11092/p/7652828.html