记录小白学习python爬虫的过程(二)
正则表达式
特殊字符
^h表示以h开头,.表示任意字符,*表示任意多次
import re
line = 'hello 123'
#^h表示以h开头,.表示任意字符,*表示任意多次**
re_str = '^h.*'
if re.match(re_str, line):
print('匹配成功') # 输出:匹配成功
$表示结尾字符
import re
line = 'hello 123'
re_str = '.*3$' # 前面可为任意多个任意字符,但结尾必须是3
if re.match(re_str, line):
print('匹配成功') # 输出:匹配成功
?表示非贪婪模式
import re
line = 'heeeello123'
re_str = '.*?(h.*?l).*' # 只要()中的子串
match_obj = re.match(re_str, line)
if match_obj:
print(match_obj.group(1)) # 输出:heeeel
# 如果去掉?,则输出:heeeell
+表示至少出现一次
import re
line = 'heeeello123'
re_str = '.*(h.+?l).*'
match_obj = re.match(re_str, line