Skip to content

Commit

Permalink
allow hyphen in field name. closes #86
Browse files Browse the repository at this point in the history
  • Loading branch information
wimglenn committed Jun 11, 2024
1 parent e0c19dc commit 9c9ec7f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
6 changes: 4 additions & 2 deletions parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ def extract_format(format, extra_types):
return locals()


PARSE_RE = re.compile(r"({{|}}|{\w*(?:\.\w+|\[[^]]+])*(?::[^}]+)?})")
PARSE_RE = re.compile(r"({{|}}|{[\w-]*(?:\.[\w-]+|\[[^]]+])*(?::[^}]+)?})")


class Parser(object):
Expand Down Expand Up @@ -619,7 +619,7 @@ def _generate_expression(self):
def _to_group_name(self, field):
# return a version of field which can be used as capture group, even
# though it might contain '.'
group = field.replace(".", "_").replace("[", "_").replace("]", "_")
group = field.replace(".", "_").replace("[", "_").replace("]", "_").replace("-", "_")

# make sure we don't collide ("a.b" colliding with "a_b")
n = 1
Expand All @@ -629,6 +629,8 @@ def _to_group_name(self, field):
group = field.replace(".", "_" * n)
elif "_" in field:
group = field.replace("_", "_" * n)
elif "-" in field:
group = field.replace("-", "_" * n)
else:
raise KeyError("duplicated group name %r" % (field,))

Expand Down
20 changes: 20 additions & 0 deletions tests/test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -763,3 +763,23 @@ def test_parser_format():
assert parser.format.format("world") == "hello world"
with pytest.raises(AttributeError):
parser.format = "hi {}"


def test_hyphen_inside_field_name():
# https://github.com/r1chardj0n3s/parse/issues/86
# https://github.com/python-openapi/openapi-core/issues/672
template = "/local/sub/{user-id}/duration"
assert parse.Parser(template).named_fields == ["user_id"]
string = "https://dummy_server.com/local/sub/1647222638/duration"
result = parse.search(template, string)
assert result["user-id"] == "1647222638"


def test_hyphen_inside_field_name_collision_handling():
template = "/foo/{user-id}/{user_id}/{user.id}/bar/"
assert parse.Parser(template).named_fields == ["user_id", "user__id", "user___id"]
string = "/foo/1/2/3/bar/"
result = parse.search(template, string)
assert result["user-id"] == "1"
assert result["user_id"] == "2"
assert result["user.id"] == "3"

0 comments on commit 9c9ec7f

Please sign in to comment.