I have a string which is a file name, examples:
JavaScript
x
3
1
'20220213-0000-FSC-814-SC_VIRG_REFBAL_PRES_NPMINMAX-v1.xml'
2
'20220213-0000-F814-SC_VIRG_REFBAL_PRES_NPMINMAX-v1.xml'
3
I want to find a string with re.search which corresponds to Fddd
or FSC-ddd
.
I have a regex like this:
JavaScript
1
2
1
type_match = re.search(r'(F(d{3}))|(FSC-(d{3}))', string)
2
Later after I have found for example FSC-814
, I want to get only the number from this found string, I used:
JavaScript
1
2
1
int(type_match.group(1))
2
but it does not work after I included or statement in the re.search
Advertisement
Answer
You can use
JavaScript
1
2
1
F(?:SC)?-?(d{3})
2
See the regex demo.
Details:
F
– anF
char(?:SC)?
– an optionalSC
char sequence-?
– an optional hyphen(d{3})
– Capturing group 1: three digits.
See the Python demo:
JavaScript
1
9
1
import re
2
texts = ['20220213-0000-FSC-814-SC_VIRG_REFBAL_PRES_NPMINMAX-v1.xml',
3
'20220213-0000-F814-SC_VIRG_REFBAL_PRES_NPMINMAX-v1.xml']
4
pattern = r'F(?:SC)?-?(d{3})'
5
for text in texts:
6
match = re.search(pattern, text)
7
if match:
8
print (match.group(1))
9
Output:
JavaScript
1
3
1
814
2
814
3