Finding multiple substrings in a string without iterating over it multiple times

后端 未结 3 610
忘了有多久
忘了有多久 2021-01-04 21:18

I need to find if items from a list appear in a string, and then add the items to a different list. This code works:

data =[]
line = \'akhgvfalfhda.dhgfa.lidh         


        
3条回答
  •  盖世英雄少女心
    2021-01-04 22:08

    One approach is to build a very simple regex pattern, and use re.findall() to find/extract any matched words in the string.

    import re
    
    line = 'akhgvfalfhda.dhgfa.lidhfalihflaih**Thing1**aoufgyafkugafkjhafkjhflahfklh**Thing2**dlfkhalfhafli...'
    _legal = ['thing1', 'thing2', 'thing3', 'thing4']
    
    exp = re.compile(r'|'.join(_legal), re.IGNORECASE)
    exp.findall(line)
    
    >>> ['Thing1', 'Thing2']
    

提交回复
热议问题