Search code examples
pythonpython-re

Extract substring from string python re library


I have a string

string = 'Ph no. : 999999999 | year: 2021 | class no.: 10Type: 2-A | S-no. : dfwef | Name : dfwf'

Using regular expression python I want to extract Type. Output I want in this case is 2-A.

I have tried is

import re
type = re.findall(r'Type: \d*-', string)
print(type)

I have multiples strings of this type and i want to extract code text between 'Type:' and '|'.


Solution

  • This should give you the needed result if Type contains only one number, '-', and a letter

    import re
    
    string = 'Ph no. : 999999999 | year: 2021 | class no.: 10Type: 2-A | S-no. : dfwef | Name : dfwf'
    
    type_str = re.search('(Type:\s\d+-\w+)', string).group()
    print(type_str)
    

    Type: 2-A

    Or if you want to extract only the 2-A

    import re
    
    string = 'Ph no. : 999999999 | year: 2021 | class no.: 10Type: 2-A | S-no. : dfwef | Name : dfwf'
    
    type_str = re.search('(Type:\s\d-\w)', string).group()
    print(type_str.split(': ')[1])
    

    2-A

    And finally as requested to extract any text from Type: to | it will be

    import re
    
    string = 'Ph no. : 999999999 | year: 2021 | class no.: 10Type: 10 X-ASFD 34 10 | S-no. : dfwef | Name : dfwf'
    
    type_str = re.search('Type:\s(.*?\|)', string).group()
    print(type_str.split(': ')[1].replace('|',''))
    

    10 X-ASFD 34 10