簡體   English   中英

匹配由空格python分隔的確切字符串

[英]match exact string separated by white spaces python

例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM