我试图使用python返回或打印在搜索关键字之前出现的特定子字符串。
例如,如果我的字符串如下所示
string = "id:0, an apple a day keeps the doctor away, id=1, oranges are orange not red, id=3, fox jumps over the dog, id=4, fox ate grapes"如果搜索关键字是apple,则应该打印0 (即id)。
如果搜索关键字是橙色的,则应该打印1 (即ids)。
如果搜索关键字为fox,则应打印3和4 (即id)。
我期待的是关键字的id,如本例所示。在我的示例中,所有可搜索的关键字都与id相关联,如示例字符串中所示。
发布于 2022-10-31 08:04:16
可以使用以下正则表达式返回索引和关键字匹配。
import re
def find_id(string, word):
pattern = r'id[:=](\d+),[\w\s]+' + word
return list(map(int, re.findall(pattern, string)))
string = "id:0, an apple a day keeps the doctor away, id=1, oranges are orange not red, id=3, fox jumps over the dog, id=4, fox ate grapes"
print(find_id(string, 'fox'))输出:
[3, 4]我已经返回了int,但是如果这不是必要的,那么您可以将返回行替换为['3', '4'],以字符串['3', '4']的形式返回索引;
return re.findall(pattern, string)https://stackoverflow.com/questions/74260133
复制相似问题