Hunt Hunt - 6 months ago 20
Python Question

optional parameter in regular expression

I want to make few paramters optional using regular expression

currently my url is


http://[ipaddress]/StoreData/10/20/30/40/50


as there are 5 numbered parameters , now sometimes i want 4 or sometime 5


i.e.
http://[ipaddress]/StoreData/10/20/30/40


should be acceptable

here is my regular expression

(?P<dataone>([0-9])+)/(?P<datatwo>([0-9])+)/(?P<datathree>([0-9])+)/(?P<datafour>([0-9])+)/(?P<datafive>([0-9])+)/

Answer

The ? modifier makes a part of a regular expression optional:

(?P<dataone>([0-9])+)/(?P<datatwo>([0-9])+)/(?P<datathree>([0-9])+)/(?P<datafour>([0-9])+)/((?P<datafive>([0-9])+)/)?

Note the (...)? around the "datafive" subpattern.