Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Match on empty string #136

Open
SeanHayes opened this issue Jul 2, 2021 · 2 comments
Open

Match on empty string #136

SeanHayes opened this issue Jul 2, 2021 · 2 comments

Comments

@SeanHayes
Copy link

I'm trying to match urls with the following pattern:

'/{url1}'

which matches '/foo' but not '/', even though '/{url1}'.format(url1='') would equal '/'.

Could this be a configurable option?

@elchupanebrej
Copy link

+1

@jenisys
Copy link
Contributor

jenisys commented Jan 2, 2022

HINT:
That is basically the case of an optional<T> item (or by using choice(s)).
You can already solve that yourself by using user-defined types (or: by using parse_type).

SEE ALSO:

OR: Use cardinality field support, like:

# -- USE CASE: Parser with CardinalityField support.
# NOTE: Automatically adds missing type variants with CardinalityField part.
from parse_type.cfparse import Parser  # DROP-IN REPLACEMENT: Parser w/ CardinalityField support
from parse import with_pattern

@with_pattern(r"\d+")
def parse_number(text):
    return int(text)

# -- PREPARE: parser, adds missing type variant for cardinality 0..1 (optional) and other cardinalities.
type_dict = dict(Number=parse_number)
parser = Parser("OptionalNumber: {number:Number?}", type_dict)

# -- USE: parser.
result1 = parser.parse("OptionalNumber: 42")
assert result1["number"] == 42
result2 = parser.parse("OptionalNumber: ")
assert result1["number"] == None

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants