簡體   English   中英

Python 正則表達式重新編譯查詢

[英]Python Regex re.compile query

我正在嘗試使用正則表達式查詢從名稱列表中找到所需名稱的列表。

csv 文件:僅供參考,我將國家/地區從大寫字母轉換為小寫字母在此處輸入圖像描述

搜索列表:

['AU.LS1_james.aus',
'AU.LS1_scott.aus',
'AP.LS1_amanda.usa',
'AP.LS1_john.usa',
'LA.LS1_harsha.ind',
'LA.LS1_vardhan.ind',
'IECAU13_peter-tu.can',
'LONSA13_smith.gbp']

搜索列表的searchList[(region)(Category)]_[EmployeeName].[country]
(region)(Category)連接在一起。

我正在嘗試獲取每個組的列表,

[
['AU.LS1_james.aus', 'AU.LS1_scott.aus'],
['AP.LS1_amanda.usa', 'AP.LS1_john.usa'],
['LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']
]

使用以下正則表達式查詢: \<({region}).*\{country}\>

for region, country in regionCountry:
    query = f"\<({region}).*\{country}\>"
    r = re.compile(query)
    group = list(filter(r.match, searchList))

我也嘗試過re.search ,但該group始終為None

僅供參考:我還在記事本++中使用正則表達式功能嘗試了這個查詢。 NOTEPAD++ 查詢:<(AU.LS1).*.aus>

誰能告訴我腳本哪里出了問題。? 謝謝

沒有正則表達式:

  1. split
  2. 以及用於對條目進行分組的字典:

數據

entries = ['AU.LS1_james.aus', 'AU.LS1_scott.aus', 'AP.LS1_amanda.usa', 'AP.LS1_john.usa', 'LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']

解決方案 1 :簡單的dictsetdefault

d = {}
for entry in entries:
    d.setdefault(entry.split('.',1)[0], []).append(entry)

解決方案2defaultdict

from collections import defaultdict
d = defaultdict(list)
for entry in entries:
    d[entry.split('.',1)[0]].append(entry)

結果d.values()

>>> list(d.values())

[['AU.LS1_james.aus', 'AU.LS1_scott.aus'],
 ['AP.LS1_amanda.usa', 'AP.LS1_john.usa'],
 ['LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']]

我感謝大家試圖協助我的問題。 這個答案很適合我的使用。 出於某種原因 python 不喜歡\<\> 所以我只是刪除了它們並且效果很好。 沒想到使用re庫會有一些限制。

答案f({region}).*\{country}

暫無
暫無

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

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