【问题标题】:match exact string separated by white spaces python匹配由空格分隔的精确字符串python
【发布时间】:2018-08-11 13:23:38
【问题描述】:

示例:

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

【问题讨论】:

    标签: python python-3.x python-2.7


    【解决方案1】:

    在正则表达式中使用分词符 (\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'], []]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 2020-10-01
      • 2017-10-30
      • 1970-01-01
      • 2021-10-18
      相关资源
      最近更新 更多