Name groups in a build-label regular expression
A build label is easier to consume when the regular expression names its semantic parts. Here, project, major, minor, and channel are named groups in the label orbit-2.14-rc. After fullmatch() verifies the complete label shape, groupdict() produces a dictionary keyed by those group names. The assertion checks every extracted string, including 14 for the minor version and rc for the channel. Printing the dictionary gives exact, predictable output for this literal insertion order.
Python uses the syntax (?P<name>...) for a named capturing group. A named group also has a numeric group number, but using names makes later code less fragile when parentheses are rearranged. Pattern.fullmatch() is used so that a valid-looking substring cannot make a longer malformed label acceptable. The official re syntax documentation describes named groups, and Match.groupdict() documents the mapping returned from a match. Named groups and groupdict() are long-standing standard-library APIs; fullmatch() requires Python 3.4 or later.
This pattern intentionally permits only lowercase ASCII project names, decimal components, and three channel words. It does not compare version numbers numerically, enforce a project catalog, or accept labels such as orbit-2.14-rc1. Also, the assertion validates this sample rather than proving the expression meets every build-system convention. Expand the alternatives only after documenting the labels your system actually emits.
AI-assistance disclosure: this article was drafted with AI assistance and checked using a synthetic example.
import re
label = re.compile(
r"(?P<project>[a-z]+)-(?P<major>\d+)\.(?P<minor>\d+)-"
r"(?P<channel>dev|rc|release)"
)
match = label.fullmatch("orbit-2.14-rc")
assert match is not None
parts = match.groupdict()
assert parts == {
"project": "orbit",
"major": "2",
"minor": "14",
"channel": "rc",
}
print(parts)
{'project': 'orbit', 'major': '2', 'minor': '14', 'channel': 'rc'}
Comments
Post a Comment