Back
Close

Programação Python (Parte 3) - Prof. MARCO VAZ

MarcoVaz
199K views

Expressões Regulares (Continuação)

Sequências especiais

Uma sequência especial inicia como uma barra () seguida por um dos caracteres da lista abaixo e tem um significado especial:
funcao

Exemplos:

import re

txt = "chove chuva chove sem parar"

#Retorna a string ch se estiver no início da frase(retorna apenas 1:

x = re.findall("\Ach", txt)

print('x1 = ',x)

Resultado:
x1 = ['ch']

import re

txt = "chove chuva chove sem parar"

#retorna a string  ch se estiver no início das palavras(retorna apenas 1:

x = re.findall(r"\bch", txt)

print('x2 = ',x)

Resultado:
x2 = ['ch', 'ch', 'ch']

import re

txt = "chove chuva chove sem parar"

#Retorna a string ch se estiver no fim das palavras(retorna apenas 1:

x = re.findall(r"ch\b", txt)

print('x3 = ',x)

Resultado:
x3 = []

import re

txt = "chove chuva chove sem parar"

#Retorna a string "ch", se estiver presente, mas NÃO no início da palavra:

x = re.findall(r"\Bch", txt)

print('x4 = ',x)

#Retorna a string "ch" se estiver presente, mas NÃO no fim da palavra:

x = re.findall(r"ch\B", txt)

print('x4 = ',x)

Resultado:
x4 = []
x4 = ['ch', 'ch', 'ch']

import re

txt = "chove chuva chove sem parar"

#Retorna os caracteres dígitos(números de 0-9), se existir

x = re.findall(r"\d", txt)

print('x5 = ',x)

Resultado:
x5 = []

import re

txt = "chove chuva chove sem parar"

#Retorna os caracteres NÃO dígitos(números de 0-9), se existir

x = re.findall(r"\D", txt)

print('x6 = ',x)

Resultado:
x6 = ['c', 'h', 'o', 'v', 'e', ' ', 'c', 'h', 'u', 'v', 'a', ' ', 'c', 'h', 'o', 'v', 'e', ' ', 's', 'e', 'm', ' ', 'p', 'a', 'r', 'a', 'r']

import re

txt = "chove chuva chove sem parar"

#Retorna apenas os espaços em branco, se existir
x = re.findall("\s", txt)
print('x7 = ',x)

Resultado:
x7 = [' ', ' ', ' ', ' ']

import re

txt = "chove chuva chove sem parar"

#Retorna os caracteres, mas NÃO os espaços em branco,  se existir
x = re.findall("\S", txt)
print('x8 = ',x)

Resultado:
x8 = ['c', 'h', 'o', 'v', 'e', 'c', 'h', 'u', 'v', 'a', 'c', 'h', 'o', 'v', 'e', 's', 'e', 'm', 'p', 'a', 'r', 'a', 'r']

import re

txt = "chove chuva chove sem parar"

#Retorna a sequência, se terminar a frase, isto é, se está no final":

x = re.findall("arar\Z", txt)

print('x9 = ',x)

Resultado:
x9 = ['arar']

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io