import re
string = "IwenttotheParkToday"
my_list = ["went", "the", "today"]
# we split on any of the words in my_list, and put it into a group
# so that it is included in the output
split_re = re.compile('(' + '|'.join(my_list) + ')', re.I)
# the regex we use will be '(went|the|today)'
# we remove empty words if one of the split strings was at the start or end
out = [word for word in split_re.split(string) if word]
print(out)
# ['I', 'went', 'to', 'the', 'Park', 'Today']
通过使用每个元素作为
str.split()
的分隔符,在my_list
上循环:您可以使用正则表达式,对任何单词进行拆分,并将拆分结果放入一个组中,以便将其保留在输出中。我们还可以使用
re.I
标志以不区分大小写的方式进行匹配:相关问题 更多 >
编程相关推荐