Registre o processo do Xiaobai learning python crawler (2)
Expressão regular
Caracteres especiais
^ h significa começar com h, significa qualquer caractere, * significa qualquer número de vezes
import re
line = 'hello 123'
#^h表示以h开头,.表示任意字符,*表示任意多次**
re_str = '^h.*'
if re.match(re_str, line):
print('匹配成功') # 输出:匹配成功
$ Significa caractere final
import re
line = 'hello 123'
re_str = '.*3$' # 前面可为任意多个任意字符,但结尾必须是3
if re.match(re_str, line):
print('匹配成功') # 输出:匹配成功
? Indica modo não ganancioso
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
+ Significa pelo menos uma vez
import re
line = 'heeeello123'
re_str = '.*(h.+?l).*'
match_obj = re.match(re_str, line)
if match_obj:
print(match_obj.group(1)) #输出:heeeel
{2} significa que o caractere anterior aparece duas vezes
import re
line = 'heeeello123'
re_str = '.*?(e.{2}?l).*' # 匹配的是e+任意2个字符+l
match_obj = re.match(re_str, line)
if match_obj:
print(match_obj.group(1)) # 输出:eeel
| Significa ou
import re
line = 'hello123'
re_str = '((hello|heeello)123)'
match_obj = re.match(re_str, line)
if match_obj:
print(match_obj.group(1)) # 输出:python123
[] indica que o intervalo de valores é fornecido para um único caractere
import re
line = 'hello123'
re_str = "([jhk]ello123)" # [jhk]表示jhk中的任一个都可以
match_obj = re.match(re_str, line)
if match_obj:
print(match_obj.group(1)) # 输出:hello123
[^] significa conjunto sem caracteres
import re
line = 'hello123'
re_str = "([^j]ello123)" # [^j]表示不是j的都行
match_obj = re.match(re_str, line)
if match_obj:
print(match_obj.group(1)) # 输出:hello123
\ s significa espaço \ S significa não espaço
import re
line = 'hello123 好' #字符串有空格
re_str = "(hello123\s好)" # 匹配上空格
match_obj = re.match(re_str, line)
if match_obj:
print(match_obj.group(1)) #输出:hello123 好
[\ u4E00- \ u9FA5] significa caracteres chineses
import re
line = 'hello 北京大学'
re_str = ".*?([\u4E00-\u9FA5]+大学)"
match_obj = re.match(re_str, line)
if match_obj:
print(match_obj.group(1)) # 输出:北京大学
Pequeno exemplo para extrair a data de nascimento
import re
line = 'xxx出生于2000年6月1日'
line = 'xxx出生于2000/6/1'
line = 'xxx出生于2000-6-1'
line = 'xxx出生于2000-06-01'
line = 'xxx出生于2000-06'
re_str = ".*出生于(\d{4}[年/-]\d{1,2}([月/-]|\d{1,2}|$))"
match_obj = re.match(re_str, line)
if match_obj:
print(match_obj.group(1))
Principais funções da biblioteca Re:
função | Descrição |
---|---|
pesquisa() | Procure a primeira posição da expressão regular em uma string e retorne o objeto de correspondência |
revanche() | Corresponde à expressão regular do início de uma string e retorna o objeto de correspondência |
re.findall () | String de pesquisa, retorna todas as strings correspondentes no tipo de lista |
re.split () | Divide uma string de acordo com o resultado correspondente da expressão regular e retorna o tipo de lista |
re.finditer () | String de pesquisa, retorna um tipo de iteração de resultado correspondente, cada elemento de iteração é um objeto de correspondência |
re.sub () | Substitua todas as substrings que correspondem a expressões regulares em uma string e retorna a string substituída |
Tipo de representação da expressão regular:
tipo de string bruto (tipo de string nativo):
A nova biblioteca usa o tipo de string bruta para representar expressões regulares, expressas como: r'text '
Por exemplo: r' [1-9] \ d {5} '
string bruta refere-se a uma string que não contém caracteres de escape
O tipo de string é mais complicado.
Por exemplo: '[1-9] \ d {5}'; '\ d {3} - \ d {8} | \ d {4} - \ d {7}'
当正则表达式包含转义符时,建议使用raw string类型来表示正则表达式。
revanche()
import re
ss = 'I love you, do you?'
res = re.match(r'((\w)+(\W))+',ss)
print(res.group())
I love you,
pesquisa()
import re
ss = 'I love you, do you?'
res = re.search(r'(\w+)(,)',ss)
#print(res)
print(res.group(0))
print(res.group(1))
print(res.group(2))
you,
you
,
Não vamos dar exemplos para os outros.
Aplicação simples de expressões regulares
1. Procure o resultado de tempo na mensagem de ping
import re
ping_ss = 'Reply from 220.181.57.216:bytes=32 time=3ms TTL=47'
res = re.search(r'(time=)(\d+\w+)+(.)+TTL',ping_ss)
print(res.group(2))
3ms
2. Usado para analisar páginas da web
import re,requests
r = requests.get('https://www.baidu.com').content.decode('utf-8')
print(r)
pt = re.compile('(\<title\>)([\S\s]+)(\<\/title\>)')
print(pt.search(r).group(2))
百度一下,你就知道
Além disso, você pode usar o "r" antes da corda para melhorar a eficiência
pt = re.compile(r'(</title>)([\S\s]+)(</title>)')