4

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()
('',)
4
  • The "" inside of 'hi ""' isn't an empty string. Commented Dec 30, 2014 at 19:47
  • @mattm The point is that the string between the "s is empty. Commented Dec 30, 2014 at 20:07
  • No. That's what I'm trying to say. There is no string between the "'s, just as there is no string between the h and the i in 'hi'. Commented Dec 30, 2014 at 20:36
  • @mattm I haven't the slightest idea what it is you're trying to say. I know there's no string between the "s. I want parse to give me back an empty string in that case. Commented Dec 30, 2014 at 20:52

1 Answer 1

5

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 ('',) {}>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.