[英]getting group using filter in a regular expression in python
我有一個帶有一組鍵的字典,我想匹配鍵中的正則表達式,並且只獲取匹配鍵上的組,所以我這樣做:
subject = re.compile(r'(*.)_id') dict = {'name': 'Robert', 'customer_id': 2, 'action_id': 5} results = list(filter(subject.match, dict)) results
給我以下
['customer_id', 'action_id']
我想獲得
['customer', 'action']
獲得此列表['customer_id', 'action_id']
您可以使用^[^_]+
正則表達式使用findall
來提取_id
之前的部分。 試試這個Python代碼,
import re
subject = re.compile(r'.*_id')
dict = {'name': 'Robert', 'customer_id': 2, 'action_id': 5}
results = list(filter(subject.match, dict))
results = [''.join(re.findall(r'^[^_]+',s)) for s in results]
print(results)
打印,
['customer', 'action']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.