如果要学会Python爬虫,那么正则表达式是不可或缺的技能。在下收集了一些关于正则表达式的代码,多多练习,多多学习
#match函数应用
import re
print(re.match("done|quit",'d!one!done'))
print(re.match("\dcom","www.4comrunoob.5com"))
#search函数应用
import re
print(re.search("done|quit",'d!one!done'))
print(re.search("\dcom","www.4comrunoob.5com"))
import re
result=re.search(r"(\w)(?!.*\1)","abc@cslg.edu.cn")
print(result)
#match对象使用,一般情况的子模式,例1
import re
m=re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
print(m.group(0))
print(m.group(1))
print(m.group(2))
print(m.group(1,2))
m=re.match(r"(\w+) \1", "Isaac Isaac, physicist")
print(m.group(0))
#match对象使用,一般情况的子模式,例2
import re
m=re.match(r"(\d+)\.(\d+)","24.556")
print(m.groups())
print(m.group(0),m.group(1),m.group(2))
#match对象使用,命名子模式,例1
import re
m=re.match(r"(?P<first_name>\w+)(?P<last_name>\w+)", "Isaac Newton, physicist")
print(m.groupdict())
print(m.group())
print(m.group("first_name"))
print(m.group("last_name"))
print(m.groups())
print(m.group(0),m.group(1),m.group(2))
#match对象使用,命名子模式,例2
m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
print(m.groupdict())
#findall函数,直接用re模块
import re
s="aabc abcd abbcd aacd"
print(re.findall("aa"