Coverage for blind_charging/re_util.py: 100%
11 statements
« prev ^ index » next coverage.py v6.5.0, created at 2023-02-17 20:36 +0000
« prev ^ index » next coverage.py v6.5.0, created at 2023-02-17 20:36 +0000
1"""A collection of useful RegExp helpers"""
2import re
3from typing import Iterable, Optional
6def re_literal_group(
7 literals: Iterable[str], capture: bool = True, name: Optional[str] = None
8) -> str:
9 """Create a RegExp group pattern out of a list of literals.
11 Sorts literals longest first in pattern to match in priority order. Values
12 are escaped when added to the pattern.
14 E.g., ["foo", "bar"] -> r"(foo|bar)"
16 :param literals: List of literal values to match
17 :param capture: Whether to format as a capturing group
18 :param name: Name of capture group (ignored if capture is False)
19 :returns: RegExp match group
20 """
21 capturing = ""
22 if not capture:
23 capturing = "?:"
24 elif name:
25 capturing = "?P<{}>".format(name)
27 priority = sorted(literals, key=lambda x: len(x), reverse=True)
28 pattern = r"|".join([re.escape(s) for s in priority])
29 return r"({}{})".format(capturing, pattern)