Como buscar como palavra de uma string em python usando regex [duplicado]

Nov 25 2020

Eu tenho uma string como

string = "Status\t\t: PASS"

Eu quero buscar apenas PASS a partir desta string e estou usando este regex.

value = re.findall("Status" + r'(.*)', string)

Mas me retorna isso

"           : PASS"

Quero que a regex ignore todos os caracteres extras, espaços, tabulações, etc. Informe-me como posso fazer isso.

Respostas

3 VivekKumar Nov 25 2020 at 13:36

Método: Usando regex () + string.punctuation Este método também usa expressões regulares, mas a função de string de obter todas as pontuações é usada para ignorar todas as marcas de pontuação e obter a string de resultado filtrada.

# Python3 code to demonstrate 
# to extract words from string 
# using regex() + string.punctuation 
import re 
import string 

# initializing string 
test_string = "Geeksforgeeks, is best @# Computer Science Portal.!!!"

# printing original string 
print ("The original string is : " + test_string) 

# using regex() + string.punctuation 
# to extract words from string 
res = re.sub('['+string.punctuation+']', '', test_string).split() 

# printing result 
print ("The list of words is : " + str(res)) 

Resultado:

The original string is : Geeksforgeeks, is best @# Computer Science Portal.!!!
The list of words is : [‘Geeksforgeeks’, ‘is’, ‘best’, ‘Computer’, ‘Science’, ‘Portal’] 
2 tshiono Nov 25 2020 at 14:25

Você poderia tentar o seguinte:

import re
string = "Status\t\t: PASS"
m = re.search(r'Status\s*:\s*(.*)', string)
print(m.group(1))

Resultado:

PASS

Explicação da regex Status\s*:\s*(.*):

  • Status\s* corresponde à substring "Status" e aos seguintes caracteres em branco, tanto quanto possível, se houver.
  • :\s* corresponde a um caractere ":" e a seguir a caracteres em branco tantos quanto possível, se houver.
  • (.*) corresponde à substring restante e o grupo de captura 1 é atribuído a ela.
1 Heo Nov 25 2020 at 14:23

Experimente isto: regex-demo

Python-source:

import re

input1 = "Status\t\t: PASS"
input2 = "Status\t\t: PASS hello"
input3 = "Status\t\t: FAIL hello world"
regex=re.compile('status\s*:\s*(\w+)',flags=re.IGNORECASE)

print(f'result of input1: \n {regex.findall(input1)}')
print(f'result of input2: \n {regex.findall(input2)}')
print(f'result of input3: \n {regex.findall(input3)}')

Resultado:

result of input1: 
 ['PASS']
result of input2: 
 ['PASS']
result of input3: 
 ['FAIL']