python - 匹配由空格分隔的精确字符串 python

标签 python python-3.x python-2.7

示例:

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/

相关文章:

python - Python 是否应该崩溃?

python - python/scipy 中的牛顿法

python - Django: 'module' 对象没有属性 'ChoiceField' , 'MultipleChoiceField'

python - 将 python 脚本输出打印到文本文件和命令窗口

python - 笨拙的 arg 检查 Python

python - 如何在子目录中创建一个 "just fits"文件的 block 设备?

python - python 中的 2 元组求和

python-3.x - 模块未找到错误: No module named 'aiohttp'

python - 在远程主机上运行脚本并查看输出

python - 如何从 pandas groupby().sum() 的输出创建一个新列?