Matching strings with re.match doesn't work

前端 未结 2 1946
别跟我提以往
别跟我提以往 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 10:04

    re.match only matches the beginning of the input string to the regular expression. So this would only work for string beginning with the strings from my_list.

    re.search on the other hand searches the entire string for a match to the regular expression.

    import re
    
    my_list = ['car', 'boat', 'truck']
    my_other_string = 'I am on a boat'
    
    my_list = re.compile(r'\b(?:%s)\b' % '|'.join(my_list))
    if re.search(my_list, my_other_string):#changed function call here
        print('yay')
    

    For the string "I am on a boat", re.match will fail because the beginning of the string is "I" which doesn't match the regular expression. re.search will also not match the first charecter but will instead go through the string until it gets to "boat", at which point it will have found a match.

    If we instead use the string "Boat is what I am on", re.match and re.search will both match the regular expression to the string because the string now starts with a match.

提交回复
热议问题