Python爬虫----正则表达式符号与方法

常用符号:

常用方法:


一:findall

1. 点号

# 导入re库文件
import re

# 点号的使用
a = "xy123"
b = re.findall('x.',a)
print(b)

c = re.findall('x..',a)
print(c)

2.星号

import re
# 星号的使用
a = "xyxy123"
b = re.findall('x*',a)
print(b)


c= re.findall('y*',a)
print(c)

3.点星号、点问号

import re
secret_code = 'hadkfalifexxIxxfasdjlja134xxlovexx23345sdfxxyouxx8dfse'
#点星号
b = re.findall('xx.*xx',secret_code)
print(b)
#点问号
c= re.findall('xx.*?xx',secret_code)
print(c)

4.混合

import re
secret_code = 'hadkfalifexxIxxfasdjlja134xxlovexx23345sdfxxyouxx8dfse'
#点星号
b = re.findall('xx.*xx',secret_code)
print('b=',b)
#点问号
c= re.findall('xx.*?xx',secret_code)
print('c=',c)

d = re.findall('xx(.*?)xx',secret_code)
print('d=',d)

for each in d:
    print (each)
    
s = '''sdfxxhello
xxfsdfxxworldxxasdf'''

e = re.findall('xx(.*?)xx',s)
print('e=',e)

f = re.findall('xx(.*?)xx',s,re.S)
print('f=',f)


二:findall  search  sub

import re
s = 'asdfxxIxx123xxlovexxdfd'
f1 = re.search('xx(.*?)xx123xx(.*?)xx',s).group(1)
print('f1=',f1)


f2 = re.search('xx(.*?)xx123xx(.*?)xx',s).group(2)
print('f2=',f2)


g1 = re.findall('xx(.*?)xx123xx(.*?)xx',s)
print('g1=',g1)
print(g1[0][1])


s1 = '123rrrr123'
h1 = re.sub('123(.*?)123','456%d456'%789,s1)
print('h1=',h1)


h2 = re.sub('123(.*?)123','456%d456'%111789,s1)
print('h2=',h2)

三:匹配数字

import re
a = 'asdf1125624sss4523'
b = re.findall("(\d+)",a)
print(b)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值