[英]Python - find all regex
我在文本文件中有假ID列表。 我想捕獲所有以“ A0015”開頭的ID。 我嘗試了其他正則表達式,但它們未捕獲最終輸出。 應該使用哪個正則表達式?
text = "Here are the fake student ids: IDs A0015-4737, IDs: A0015-384721-ADA2ad, A0015WE382 \n A00152838. Please enter this."
capture_id_list = (re.findall(r"A0015 ([\w-]+)", text,flags=re.IGNORECASE))
print(capture_id_list) # results with []
# print(text.startswith('A0015')) # Gives False...not usefull
find_this = "A0015"
capture_id_list = text[:text.find(find_this) + len(find_this)]
print(capture_id_list) # Here are the fake student ids: IDs A0015. Not the results
最終輸出:
['A0015-4737','A0015-384721-ADA2ad','A0015WE382','A00152838']
我建議在您的代碼中使用r"(A0015[^ ,.]+)"
:
>>>import re
>>>text = "Here are the fake student ids: IDs A0015-4737, IDs: A0015-384721-ADA2ad, A0015WE382 \n A00152838. Please enter this."
>>>capture_id_list = (re.findall(r"(A0015[^ ,.]+)", text,flags=re.IGNORECASE))
>>>print(capture_id_list)
['A0015-4737', 'A0015-384721-ADA2ad', 'A0015WE382', 'A00152838']
這里()是捕獲組。 它捕獲一個以A0015開頭的字符串,以及一個或多個與空格,逗號或點(在[]括號中的字符用^符號否定的字符)不同的字符(+符號)。
這應該對您r"(A0015[^\\s,.]*)"
: r"(A0015[^\\s,.]*)"
,內聯看起來像這樣:
capture_id_list = (re.findall(r"(A0015[^\s,.]*)", text,flags=re.IGNORECASE))
(A0015[^\\s,.]*)
(A0015[^\\s,.]*)
A0015
從字面上匹配字符A0015
(不區分大小寫) [^\\s,.]*
*
量詞 -在零和無限制的時間之間進行匹配,並盡可能多地匹配,並根據需要返回(貪婪) \\s
匹配任何空格字符(等於[\\r\\n\\t\\f\\v ]
) ,.
匹配列表中的單個字符,.
(不區分大小寫)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.