簡體   English   中英

python使用正則表達式查找給定字符串中多個字符串的所有匹配項?

[英]python find all matches of multiple strings in a given string using regex?

我有以下模式的字符串。

string = "'L3-OPS-AB-1499', 'L3-RBP_C-449', 'L2-COM-310', 'L2-PLT-16796'"

我的要求是使用正則表達式查找以下模式的所有出現

L開頭的字符串

跟一個數字

連字符

然后是特殊關鍵字,例如“ OPS-AB”或“ PLT”或“ COM”

然后是連字符

跟一個數字

例如:L3-OPS-AB-1499

我嘗試了以下正則表達式,但給出了部分結果

regex = re.search("L\d-(OPS|RBP_|-AB|C)|(COM|PLT)-\d+",string)

我的輸出

'COM-310'

預期產量

'L3-OPS-AB-1499', 'L3-RBP_C-449', 'L2-COM-310', 'L2-PLT-16796'

任何幫助將不勝感激,謝謝

使用re.findall

>>> re.findall(r'L\d+-(?:OPS-AB|PLT|COM|RBP_C)-\d+', string)
['L3-OPS-AB-1499', 'L3-RBP_C-449', 'L2-COM-310', 'L2-PLT-16796']

暫無
暫無

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

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