示例:
strings_to_search = ['abc', 'def', 'fgh hello']
complete_list = ['abc abc dsss abc', 'defgj', 'abc fgh hello xabd', 'fgh helloijj']
for col_key in strings_to_search:
print(list(map(lambda x: re.findall(col_key, x), complete_list)))
通过运行上述程序,我们得到以下输出,我能够匹配 abc 4 次,因为它在 Complete_list 的第 0 个索引中匹配 3 次,在第 2 个索引中匹配 1 次。
“def”与“defgj”匹配,但我只想在存在“def abc”或“def”等字符串时进行匹配。 (用空格分隔或匹配字符串的开头和结尾)
类似地,“fgh hello”与“abc fgh hello xabd”和“fgh helloijj”匹配。我希望它仅与“abc fgh hello xabd”匹配,因为它是用空格分隔的。谁能建议我如何在 python 中实现这一点?
[['abc', 'abc', 'abc'], [], ['abc'], []]
[[], ['def'], [], []]
[[], [], ['fgh hello'], ['fgh hello']]
最佳答案
在正则表达式中使用分词符 (\b)。
import re
strings_to_search = ['abc', 'def', 'fgh hello']
complete_list = ['abc abc dsss abc', 'defgj', 'abc fgh hello xabd', 'fgh helloijj']
for col_key in strings_to_search:
word = r'\b{}\b'.format(col_key)
print(list(map(lambda x: re.findall(word, x), complete_list)))
输出:
[['abc', 'abc', 'abc'], [], ['abc'], []]
[[], [], [], []]
[[], [], ['fgh hello'], []]
关于python - 匹配由空格分隔的精确字符串 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49084198/