亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 python regex 查找所有出現的多個 regex 條件

使用 python regex 查找所有出現的多個 regex 條件

三國紛爭 2022-06-07 19:58:29
給定 2 種不同的正則表達式模式,我想找到這 2 種模式的所有出現。如果只有模式 1 匹配,則返回,如果只有模式 2 匹配,則返回,如果模式 1 和模式 2 匹配,則返回兩者。那么我如何在一個語句中運行多個(在本例中為 2 個正則表達式)?給定輸入字符串:"https://test.com/change-password?secret=12345;[email protected];previous_password=hello;new=1"我只想獲得電子郵件和秘密的價值。所以我希望輸出為['12345', '[email protected]']import reprint(re.search(r"(?<=secret=)[^;]+", s).group())print(re.search(r"(?<=email=)[^;]+", s).group())我可以通過多次運行正則表達式來獲得預期的輸出。我如何在單個語句中實現它?我不想運行 re.search 2 次。我可以在一個搜索語句中實現這一目標嗎?
查看完整描述

3 回答

?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

>>> re.findall(r"((?:(?<=email=)|(?<=secret=))[^;]+)", s)

['12345', '[email protected]']

但是現在您需要一種方法來識別哪些結果值是秘密,哪些是電子郵件。我建議還使用正則表達式提取此信息(這也消除了后視):


>>> dict(kv.split('=') for kv in re.findall(r"((?:secret|email)=[^;]+)", s))

{'secret': '12345', 'email': '[email protected]'}


查看完整回答
反對 回復 2022-06-07
?
守著星空守著你

TA貢獻1799條經驗 獲得超8個贊

import re


print(re.findall("(?<=secret=)[^;]+|(?<=email=)[^;]+", s))


# output

# ['12345', '[email protected]']


查看完整回答
反對 回復 2022-06-07
?
翻翻過去那場雪

TA貢獻2065條經驗 獲得超14個贊

您可以使用 dict 理解:


import re

url = "https://test.com/change-password?secret=12345;[email protected];previous_password=hello;new=1"


rx = re.compile(r'(?P<key>\w+)=(?P<value>[^;]+)')


dict_ = {m['key']: m['value'] for m in rx.finditer(url)}


# ... then afterwards ...

lst_ = [value for key in ("secret", "email") if key in dict_ for value in [dict_[key]]]

print(lst_)

# ['12345', '[email protected]']


查看完整回答
反對 回復 2022-06-07
  • 3 回答
  • 0 關注
  • 195 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號