Matching strings with re.match doesn't work

前端 未结 2 1937
别跟我提以往
别跟我提以往 2020-12-21 09:24

From this link I used the following code:

my_other_string = \'the_boat_has_sunk\'
my_list = [\'car\', \'boat\', \'truck\']
my_list = re.compile(r\'\\b(?:%s)\         


        
2条回答
  •  死守一世寂寞
    2020-12-21 09:54

    This is not a regular sentence where words are joined with an underscore. Since you are just checking if the word is present, you may either remove \b (as it is matching on a word boundary and _ is a word character!) or add alternatives:

    import re
    my_other_string = 'the_boat_has_sunk'
    my_list = ['car', 'boat', 'truck']
    my_list = re.compile(r'(?:\b|_)(?:%s)(?=\b|_)' % '|'.join(my_list))
    if re.search(my_list, my_other_string):
        print('yay')
    

    See IDEONE demo

    EDIT:

    Since you say it has to be true if one of the words in the list is in the string, not only as a separate word, but it musn't match if for example boathouse is in the string, I suggest first replacing non-word characters and _ with space, and then using the regex you had with \b:

    import re
    my_other_string = 'the_boathouse_has_sunk'
    my_list = ['car', 'boat', 'truck']
    my_other_string = re.sub(r'[\W_]', ' ', my_other_string)
    my_list = re.compile(r'\b(?:%s)\b' % '|'.join(my_list))
    if re.search(my_list, my_other_string):
        print('yay')
    

    This will not print yay, but if you remove house, it will.

    See IDEONE Demo 2

提交回复
热议问题