Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Optional Match Groups

Tags:

python

regex

I have the following that I need to place into match groups.

a = '1,2,3(1)'
b = '1,2,3'

parsing a is fine,

>>> m = re.match('^([0-9,-,\,]*)(\([0-9]*\))',a)
>>> m.groups()
('1,2,3', '(1)')

I just need to confirm how to make the second match group optional so I can parse the variable b.

like image 448
felix001 Avatar asked Sep 05 '25 03:09

felix001


1 Answers

m = re.match('^([0-9,-,\,]*)(\([0-9]*\))?',a)

                                       ^^

This should do it for you

like image 180
vks Avatar answered Sep 07 '25 20:09

vks