我有一個字串,它是一個檔案名,例如:
'20220213-0000-FSC-814-SC_VIRG_REFBAL_PRES_NPMINMAX-v1.xml'
'20220213-0000-F814-SC_VIRG_REFBAL_PRES_NPMINMAX-v1.xml'
我想用 re.search 找到一個對應于Fdddor的字串FSC-ddd。
我有一個像這樣的正則運算式:
type_match = re.search(r'(F(\d{3}))|(FSC-(\d{3}))', string)
后來在我找到例如之后FSC-814,我只想從這個找到的字串中獲取數字,我使用了:
int(type_match.group(1))
但在我包含或宣告后它不起作用re.search
uj5u.com熱心網友回復:
您可以使用
F(?:SC)?-?(\d{3})
請參閱正則運算式演示。
詳情:
F- 一個F字符(?:SC)?- 一個可選的SC字符序列-?- 一個可選的連字符(\d{3})- 捕獲組 1:三位數。
請參閱Python 演示:
import re
texts = ['20220213-0000-FSC-814-SC_VIRG_REFBAL_PRES_NPMINMAX-v1.xml',
'20220213-0000-F814-SC_VIRG_REFBAL_PRES_NPMINMAX-v1.xml']
pattern = r'F(?:SC)?-?(\d{3})'
for text in texts:
match = re.search(pattern, text)
if match:
print (match.group(1))
輸出:
814
814
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496154.html
