gpt4 book ai didi

python - 使用 re.match 匹配字符串不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 12:58:41 25 4
gpt4 key购买 nike

来自 this链接我使用了以下代码:

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.match(my_list, my_other_string):
print('yay')

但是它不起作用。我尝试在 re.compile 之后打印 my_list,它打印了这个:

re.compile('\\b(?:car|boot|truck)\\b')

我做错了什么?

最佳答案

re.match仅将输入字符串的开头与正则表达式匹配。所以这只适用于以 my_list 中的字符串开头的字符串。

re.search另一方面搜索整个字符串以匹配正则表达式。

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

对于字符串"I am on a boat"re.match 将失败,因为字符串的开头是“I”,与正则不匹配表达。 re.search 也不会匹配第一个字符,而是会遍历字符串直到到达“boat”,此时它会找到匹配项。

如果我们改为使用字符串 "Boat is what I am on"re.matchre.search 都将匹配字符串的正则表达式,因为字符串现在以匹配项开头。

关于python - 使用 re.match 匹配字符串不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30383659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com