Jak pobrać jako słowo z łańcucha w Pythonie za pomocą wyrażenia regularnego [duplikat]

Nov 25 2020

Mam taki sznurek

string = "Status\t\t: PASS"

Chcę pobrać tylko PASS z tego ciągu i używam tego wyrażenia regularnego.

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

Ale zwraca mi to

"           : PASS"

Chcę, aby wyrażenie regularne ignorowało wszystkie dodatkowe znaki, spacje, tabulatory itp. Daj mi znać, jak mam to zrobić.

Odpowiedzi

3 VivekKumar Nov 25 2020 at 13:36

Metoda: użycie regex () + string.punctuation Ta metoda również używa wyrażeń regularnych, ale funkcja string pobierająca wszystkie znaki interpunkcyjne służy do ignorowania wszystkich znaków interpunkcyjnych i pobierania przefiltrowanego ciągu wynikowego.

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

Wynik:

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

Czy mógłbyś spróbować następujących rzeczy:

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

Wynik:

PASS

Wyjaśnienie wyrażenia regularnego Status\s*:\s*(.*):

  • Status\s* dopasowuje podłańcuch „Status” i następujące puste znaki, jeśli to możliwe, jeśli istnieją.
  • :\s* dopasowuje znak „:” i następujące po nim puste znaki tak dużo, jak to możliwe, jeśli istnieją.
  • (.*) dopasowuje pozostały podciąg i jest do niego przypisywana grupa przechwytywania 1.
1 Heo Nov 25 2020 at 14:23

Spróbuj tego: regex-demo

Źródło Pythona:

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

Wynik:

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