正则表达学习笔记

1. 基础

^b代表字符串必须以b开头
3$代表必须以3结尾
.代表任意字符
*代表前面字符可以重复任意多次
1+代表1至少出现一次
(w.{2}w)w与w中间的字符出现2次
{3,}最少3次
{3,6}最少3次,最多6次

import re
line = "wuwei123"
regex_str = "^w.*3$"   
if re.match(regex_str, line):
	print ("yes")
>>> yes

2. 贪婪模式匹配

//假设我们希望提取"wuuuuuuuuuuuuuw"字符串
import re
line = "wuuuuuuuuuuuuuwwei123"
regex_str = ".*(w.*w).*"
match_obj = re.match(regex_str, line)
if match_obj:
	print (match_obj.group(1))
>>> ww
//原因:反向匹配

用?变为非贪婪模式匹配,从左边开始匹配

regex_str = ".*?(w.*w).*"
>>> wuuuuuuuuuuuuuww
regex_str = ".*?(w.*?w).*"
>>> wuuuuuuuuuuuuuw

3.其它

[ ] 满足中括号内任意一个字符都能匹配

[^1] 不等于1
[0-9] 0-9任意一个
.*在[ ]中没有特殊含义

\s 为空格
\S 不为空格
\w 相当于[A-Za-z0-9_]
\W 与\w相反
[\u4E00-\u9FA5] 汉字

例1:

line = "study in 电子科技大学"
regex_str = ".*([\u4E00-\u9FA5]+大学)"
match_obj = re.match(regex_str, line)
if match_obj:
	print (match_obj.group(1))
>>> 技大学
// 贪婪匹配
line = "study in 电子科技大学"
regex_str = ".*?([\u4E00-\u9FA5]+大学)"
match_obj = re.match(regex_str, line)
if match_obj:
	print (match_obj.group(1))
>>> 电子科技大学

例2:

line = "XXXX出生于9102年"
regex_str = ".*?(\d+)年"
//regex_str = ".*?(\d{4})年"
match_obj = re.match(regex_str, line)
if match_obj:
	print (match_obj.group(1))
>>> 9102

例3:

line = "XXXX出生于2001年6月1日"
#line = "XXXX出生于2001/6/1"
#line = "XXXX出生于2001-6-1"
#line = "XXXX出生于2001-06-01"
#line = "XXXX出生于2001-06"
regex_str = ".*?(\d+)年"
//regex_str = ".*出生于(\d{4}[年/-]\d{1,2}([月/-]\d{1,2}|[月/-]$|$))"
match_obj = re.match(regex_str, line)
if match_obj:
	print (match_obj.group(1))
>>> 9102

你可能感兴趣的:(爬虫)