How to fetch as word from a string in python using regex

I have a string like

string = "Status\t\t: PASS"

I want to fetch only PASS from this string and I am using this regex.

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

But it returns me this

"           : PASS"

I want the regex to ignore all extra characters spaces tabs etc. Please let me know how can I do this.

3 answers

  • answered 2020-11-25 06:36 Vivek Kumar

    Method : Using regex() + string.punctuation This method also used regular expressions, but string function of getting all the punctuations is used to ignore all the punctuation marks and get the filtered result string.

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

    Output:

    The original string is : Geeksforgeeks, is best @# Computer Science Portal.!!!
    The list of words is : [‘Geeksforgeeks’, ‘is’, ‘best’, ‘Computer’, ‘Science’, ‘Portal’] 
    

  • answered 2020-11-25 07:23 Heo

    Try this: 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)}')
    

    Out-put:

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

  • answered 2020-11-25 07:25 tshiono

    Would you please try the following:

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

    Output:

    PASS
    

    Explanation of the regex Status\s*:\s*(.*):

    • Status\s* matches substring "Status" and following blank characters as may as possible if any.
    • :\s* matches a character ":" and following blank characters as many as possible if any.
    • (.*) matches the remaining substring and capture group 1 is assigned to it.