Come recuperare come parola da una stringa in Python usando regex [duplicate]

Nov 25 2020

Ho una stringa come

string = "Status\t\t: PASS"

Voglio recuperare solo PASS da questa stringa e sto usando questa regex.

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

Ma questo mi restituisce

"           : PASS"

Voglio che la regex ignori tutte le tabulazioni di spazi di caratteri extra ecc. Per favore fatemi sapere come posso farlo.

Risposte

3 VivekKumar Nov 25 2020 at 13:36

Metodo: utilizzo di regex () + string.punctuation Questo metodo utilizzava anche espressioni regolari, ma la funzione stringa per ottenere tutti i segni di punteggiatura viene utilizzata per ignorare tutti i segni di punteggiatura e ottenere la stringa di risultato filtrata.

# 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)) 

Produzione:

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

Potresti provare quanto segue:

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

Produzione:

PASS

Spiegazione della regex Status\s*:\s*(.*):

  • Status\s* corrisponde alla sottostringa "Stato" e ai seguenti caratteri vuoti il ​​più possibile, se presenti.
  • :\s* corrisponde a un carattere ":" e seguenti caratteri vuoti il ​​maggior numero possibile di caratteri.
  • (.*) corrisponde alla sottostringa rimanente e ad essa viene assegnato il gruppo di cattura 1.
1 Heo Nov 25 2020 at 14:23

Prova questo: regex-demo

Fonte Python:

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)}')

Produzione:

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