Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python parse empty string

Tags:

python

I'm using the parse library and ran into surprising (to me) functionality: it does not match empty strings:

>>> from parse import parse
>>> parse('hi "{}"', 'hi "everybody"')
<Result ('everybody',) {}>
>>> parse('hi "{}"', 'hi ""')
>>> 

Is there a way, using parse, to get it to match any string between "" in the same way that re does:

>>> from re import match
>>> match('hi "(.*)"', 'hi "everybody"').groups()
('everybody',)
>>> match('hi "(.*)"', 'hi ""').groups()
('',)
like image 638
Barry Avatar asked Sep 16 '25 21:09

Barry


1 Answers

Use a custom type conversion:

from parse import parse
def zero_or_more_string(text):
    return text

zero_or_more_string.pattern = r".*"
parse('hi "{:z}"', 'hi ""', { "z": zero_or_more_string })

and you'll get this:

<Result ('',) {}>
like image 158
David K. Hess Avatar answered Sep 19 '25 10:09

David K. Hess