Thursday, March 19, 2015

Where to put the optional marker in a regex?


I'm looking back at my AIS VDM python regular expressions this morning.  It seems obvious now that I look at this code block, but when a field is missing, I'd rather get a None back, so the "?" goes outside the named regex block.

ipython

In [1]: import re

In [2]: a = re.compile(r'(?P<seq_id>[0-9]?)')

In [3]: b = re.compile(r'(?P<seq_id>[0-9])?')

In [4]: a.match('').groupdict()
Out[4]: {'seq_id': ''}

In [5]: b.match('').groupdict()

Out[5]: {'seq_id': None}


No comments:

Post a Comment