diff --git a/CHANGELOG.md b/CHANGELOG.md index 10f57e0..da57838 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Python JSONPath Change Log -# 2.2.3 (unreleased) +# 2.3.0 (unreleased) **Fixes** @@ -10,6 +10,11 @@ - Fixed JSONPath property name parsing to accept the full range of allowed Unicode code points and reject names containing a hyphen (`-`) in strict mode. - Fixed parsing of JSONPath string literals containing escape sequences less than or equal to `\u001F`. Previously we would incorrectly reject such escape sequences, now they are allowed. +**Changes** + +- Removed the `iregexp-check` dependency. We now include faster and more correct implementations of `check_iregexp` and `map_iregexp` in this project. +- Added the `check_iregexp` argument to `jsonpath.function_extensions.Match` and `jsonpath.function_extensions.Search` for controlling I-Regexp validation. By default, `check_iregexp` is `True` if the `regex` package is installed. + # Version 2.2.2 **Fixes** diff --git a/docs/index.md b/docs/index.md index e9fd751..79633c1 100644 --- a/docs/index.md +++ b/docs/index.md @@ -46,10 +46,7 @@ For strict compliance with the specification, [strict mode](syntax.md) and the ` pip install python-jsonpath[strict] ``` -This installs [`regex`](https://pypi.org/project/regex/) and [`iregexp-check`](https://pypi.org/project/iregexp-check/), enabling: - -- [`match()`](functions.md#match) and [`search()`](functions.md#search) to use `regex` instead of Python's built-in `re` module. -- Validation of regular expressions against [RFC 9485](https://datatracker.ietf.org/doc/html/rfc9485). +This installs [`regex`](https://pypi.org/project/regex/), allowing [`match()`](functions.md#match) and [`search()`](functions.md#search) to use `regex` instead of Python's built-in `re` module. See the [syntax guide](syntax.md) for strict mode details and specification extensions. diff --git a/jsonpath/__about__.py b/jsonpath/__about__.py index 74a8aff..7a5a1a3 100644 --- a/jsonpath/__about__.py +++ b/jsonpath/__about__.py @@ -1,4 +1,4 @@ # SPDX-FileCopyrightText: 2023-present James Prior # # SPDX-License-Identifier: MIT -__version__ = "2.2.3" +__version__ = "2.3.0" diff --git a/jsonpath/_iregexp.py b/jsonpath/_iregexp.py new file mode 100644 index 0000000..1d08110 --- /dev/null +++ b/jsonpath/_iregexp.py @@ -0,0 +1,317 @@ +from typing import Tuple + +_VALID_UNICODE_CATEGORIES = frozenset( + [ + "L", + "M", + "N", + "P", + "S", + "Z", + "C", + "Lu", + "Ll", + "Lt", + "Lm", + "Lo", + "Mn", + "Mc", + "Me", + "Nd", + "Nl", + "No", + "Pc", + "Pd", + "Ps", + "Pe", + "Pi", + "Pf", + "Po", + "Sm", + "Sc", + "Sk", + "So", + "Zs", + "Zl", + "Zp", + "Cc", + "Cf", + "Cn", + "Co", + "Cs", + ] +) + +_ALLOWED_SINGLE_CHAR_ESCAPES = frozenset("()*+-.?[\\]^nrt{|}") + + +def check_iregexp(pattern: str) -> bool: # noqa: PLR0911, PLR0912 + """Return True if `pattern` conforms to RFC 9485, or False otherwise.""" + pos = 0 + length = len(pattern) + group_depth = 0 + expect_atom = True + + while pos < length: + ch = pattern[pos] + + if ch == "(": + group_depth += 1 + pos += 1 + expect_atom = True + + elif ch == ")": + if group_depth == 0: + return False + group_depth -= 1 + pos += 1 + expect_atom = False + + # Branch + elif ch == "|": + pos += 1 + expect_atom = True + + # Single-character quantifiers + elif ch in "*+?": + if expect_atom: + return False + pos += 1 + expect_atom = True # Disallow stacked quantifiers like '++' or '*+' + + # Range quantifiers {n}, {n,}, {n,m} + elif ch == "{": + if expect_atom: + return False + pos = _check_range_quantifier(pattern, pos + 1, length) + if pos == -1: + return False + expect_atom = True + + # Character classes [...] + elif ch == "[": + pos = _check_char_class(pattern, pos + 1, length) + if pos == -1: + return False + expect_atom = False + + # Escape sequences (\) + elif ch == "\\": + pos = _check_escape(pattern, pos + 1, length) + if pos == -1: + return False + expect_atom = False + + # Disallowed unescaped closing symbols + elif ch in "]}": + return False + + # Literal character + else: + pos += 1 + expect_atom = False + + return group_depth == 0 + + +def _check_char_class(pattern: str, pos: int, length: int) -> int: # noqa: PLR0911 + if pos >= length: + return -1 + + if pattern[pos] == "^": + pos += 1 + + has_item = False + + # Optional leading '-' + if pos < length and pattern[pos] == "-": + has_item = True + pos += 1 + + while pos < length: + ch = pattern[pos] + + if ch == "]": + return (pos + 1) if has_item else -1 + + # Optional trailing '-' right before ']' + if ch == "-" and pos + 1 < length and pattern[pos + 1] == "]": + return pos + 2 + + # Parse CCE1 atom + pos, is_cc = _parse_cc_atom(pattern, pos, length) + if pos == -1: + return -1 + + has_item = True + + # Check for range: CCchar "-" CCchar + if is_cc and pos < length and pattern[pos] == "-": + if pos + 1 < length and pattern[pos + 1] == "]": + # Trailing '-' + return pos + 2 + + pos += 1 # Skip range '-' + pos, is_cc = _parse_cc_atom(pattern, pos, length) + if pos == -1 or not is_cc: + return -1 + + return -1 + + +def _parse_cc_atom(pattern: str, pos: int, length: int) -> Tuple[int, bool]: # noqa: PLR0911 + """Return (next_pos, is_ccchar).""" + if pos >= length: + return -1, False + + ch = pattern[pos] + if ch == "\\": + if pos + 1 >= length: + return -1, False + + esc = pattern[pos + 1] + + if esc in _ALLOWED_SINGLE_CHAR_ESCAPES: + return pos + 2, True # SingleCharEsc is a valid CCchar + + if esc in "pP": + if pos + 2 >= length or pattern[pos + 2] != "{": + return -1, False + + close_b = pattern.find("}", pos + 3) + if close_b == -1: + return -1, False + + if pattern[pos + 3 : close_b] not in _VALID_UNICODE_CATEGORIES: + return -1, False + + return (close_b + 1, False) + + return -1, False + + if ch in "-[]": + # Unescaped '-', '[', and ']' are excluded from CCchar + return -1, False + + return pos + 1, True + + +def _check_escape(pattern: str, pos: int, length: int) -> int: # noqa: PLR0911 + if pos >= length: + return -1 + + esc = pattern[pos] + + if esc in _ALLOWED_SINGLE_CHAR_ESCAPES: + return pos + 1 + + if esc in "pP": + pos += 1 + if pos >= length or pattern[pos] != "{": + return -1 + pos += 1 + close_bracket = pattern.find("}", pos) + if close_bracket == -1: + return -1 + + prop_name = pattern[pos:close_bracket] + if prop_name not in _VALID_UNICODE_CATEGORIES: + return -1 + + return close_bracket + 1 + + return -1 + + +def _check_range_quantifier(pattern: str, pos: int, length: int) -> int: + has_initial_digits = False + comma_found = False + + while pos < length: + ch = pattern[pos] + + if ch.isdigit(): + if not comma_found: + has_initial_digits = True + pos += 1 + + elif ch == ",": + if comma_found or not has_initial_digits: + return -1 + comma_found = True + pos += 1 + + elif ch == "}": + if not has_initial_digits: + return -1 + return pos + 1 + + else: + return -1 + + return -1 + + +def map_iregexp(pattern: str, *, escape_anchors: bool = True, wrap: bool = True) -> str: + r"""Map I-Regexp `pattern` to a "regex" pattern. + + Assumes `pattern` has already passed RFC 9485 validation. + + Arguments: + pattern: A regular expression pattern following RFC 9485 syntax. + escape_anchors: When True, treat `^` and `$` as normal characters. + wrap: When True, wrap the result in `^(?:` and `)$`. + + Returns: + A regular expression pattern suitable for the "regex" package. The result + is not guaranteed to be compatible with Python's "re" module due to the + lack of support for `\p{..}` and `\P{..}` escape sequences. + """ + out = ["^(?:"] if wrap else [] + pos = 0 + length = len(pattern) + + while pos < length: + ch = pattern[pos] + + # Dot outside character classes maps to [^\n\r] + if ch == ".": + out.append(r"[^\n\r]") + pos += 1 + + # Literal ^ and $ outside char classes must be escaped + elif escape_anchors and ch in "^$": + out.append("\\") + out.append(ch) + pos += 1 + + elif ch == "[": + out.append("[") + pos += 1 + while pos < length: + c = pattern[pos] + out.append(c) + pos += 1 + if c == "\\": + if pos < length: + out.append(pattern[pos]) + pos += 1 + elif c == "]": + break + + elif ch == "\\": + out.append("\\") + pos += 1 + if pos < length: + out.append(pattern[pos]) + pos += 1 + + # 5. All other literal characters + else: + out.append(ch) + pos += 1 + + if wrap: + out.append(")$") + + return "".join(out) diff --git a/jsonpath/env.py b/jsonpath/env.py index 26a5392..ebbc11a 100644 --- a/jsonpath/env.py +++ b/jsonpath/env.py @@ -9,13 +9,6 @@ except ImportError: REGEX_AVAILABLE = False # type: ignore -try: - import iregexp_check # type: ignore # noqa: F401 - - IREGEXP_AVAILABLE = True -except ImportError: - IREGEXP_AVAILABLE = False # type: ignore - from decimal import Decimal from operator import getitem from typing import TYPE_CHECKING @@ -184,12 +177,8 @@ def __init__( self.regex_available: bool = REGEX_AVAILABLE """When `True`, the third party `regex` package is available.""" - self.iregexp_available: bool = IREGEXP_AVAILABLE - """When `True`, the iregexp_check package is available. - - iregexp_check will be used to validate regular expressions against RFC 9485, - if available. - """ + self.iregexp_available: bool = True + """Always True since version 2.3.0. I-Regexp validation is now built-in.""" self.lexer: Lexer = self.lexer_class(env=self) """The lexer bound to this environment.""" diff --git a/jsonpath/function_extensions/_pattern.py b/jsonpath/function_extensions/_pattern.py index d505f29..3892445 100644 --- a/jsonpath/function_extensions/_pattern.py +++ b/jsonpath/function_extensions/_pattern.py @@ -1,5 +1,5 @@ -from typing import List from typing import Optional +from typing import Sequence try: import regex as re @@ -10,19 +10,15 @@ REGEX_AVAILABLE = False -try: - from iregexp_check import check - - IREGEXP_AVAILABLE = True -except ImportError: - IREGEXP_AVAILABLE = False - from jsonpath.exceptions import JSONPathError from jsonpath.function_extensions import ExpressionType from jsonpath.function_extensions import FilterFunction from jsonpath.lru_cache import LRUCache from jsonpath.lru_cache import ThreadSafeLRUCache +from .._iregexp import check_iregexp +from .._iregexp import map_iregexp + class AbstractRegexFilterFunction(FilterFunction): """Base class for filter function that accept regular expression arguments. @@ -34,10 +30,12 @@ class AbstractRegexFilterFunction(FilterFunction): silently ignores bad patterns. thread_safe: When `True`, use a `ThreadSafeLRUCache` instead of an instance of `LRUCache`. + check_iregexp: When `True`, check regular expression patterns for + I-Regexp compliance. """ - arg_types = [ExpressionType.VALUE, ExpressionType.VALUE] - return_type = ExpressionType.LOGICAL + arg_types: Sequence[ExpressionType] = [ExpressionType.VALUE, ExpressionType.VALUE] + return_type: ExpressionType = ExpressionType.LOGICAL def __init__( self, @@ -45,6 +43,7 @@ def __init__( cache_capacity: int = 300, debug: bool = False, thread_safe: bool = False, + check_iregexp: bool = REGEX_AVAILABLE, ): self.cache: LRUCache[str, Optional[re.Pattern]] = ( # type: ignore ThreadSafeLRUCache(capacity=cache_capacity) @@ -52,6 +51,7 @@ def __init__( else LRUCache(capacity=cache_capacity) ) + self.check_iregexp = check_iregexp self.debug = debug def check_cache(self, pattern: str) -> Optional[re.Pattern]: # type: ignore @@ -59,7 +59,7 @@ def check_cache(self, pattern: str) -> Optional[re.Pattern]: # type: ignore try: _pattern = self.cache[pattern] except KeyError: - if IREGEXP_AVAILABLE and not check(pattern): + if self.check_iregexp and not check_iregexp(pattern): if self.debug: raise JSONPathError( "search pattern is not a valid I-Regexp", token=None @@ -67,7 +67,7 @@ def check_cache(self, pattern: str) -> Optional[re.Pattern]: # type: ignore _pattern = None else: if REGEX_AVAILABLE: - pattern = map_re(pattern) + pattern = map_iregexp(pattern, escape_anchors=False, wrap=False) try: _pattern = re.compile(pattern) @@ -79,34 +79,3 @@ def check_cache(self, pattern: str) -> Optional[re.Pattern]: # type: ignore self.cache[pattern] = _pattern return _pattern - - -def map_re(pattern: str) -> str: - """Convert an I-Regexp pattern into a Python re pattern.""" - escaped = False - char_class = False - parts: List[str] = [] - for ch in pattern: - if escaped: - parts.append(ch) - escaped = False - continue - - if ch == ".": - if not char_class: - parts.append(r"(?:(?![\r\n])\P{Cs}|\p{Cs}\p{Cs})") - else: - parts.append(ch) - elif ch == "\\": - escaped = True - parts.append(ch) - elif ch == "[": - char_class = True - parts.append(ch) - elif ch == "]": - char_class = False - parts.append(ch) - else: - parts.append(ch) - - return "".join(parts) diff --git a/jsonpath/function_extensions/filter_function.py b/jsonpath/function_extensions/filter_function.py index 7391323..ff8c565 100644 --- a/jsonpath/function_extensions/filter_function.py +++ b/jsonpath/function_extensions/filter_function.py @@ -1,9 +1,10 @@ """Classes modeling the JSONPath spec type system for function extensions.""" + from abc import ABC from abc import abstractmethod from enum import Enum from typing import Any -from typing import List +from typing import Sequence class ExpressionType(Enum): @@ -19,7 +20,7 @@ class FilterFunction(ABC): @property @abstractmethod - def arg_types(self) -> List[ExpressionType]: + def arg_types(self) -> Sequence[ExpressionType]: """Argument types expected by the filter function.""" @property diff --git a/pyproject.toml b/pyproject.toml index e7dca3c..a26215b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,7 +35,7 @@ Issues = "https://github.com/jg-rp/python-jsonpath/issues" Source = "https://github.com/jg-rp/python-jsonpath" [project.optional-dependencies] -strict = ["regex", "iregexp-check>=0.1.4"] +strict = ["regex"] [tool.hatch.version] path = "jsonpath/__about__.py" @@ -55,7 +55,6 @@ dependencies = [ "pytest-cov", "mypy", "regex", - "iregexp-check", "pyyaml", "types-pyyaml", "types-regex", @@ -187,7 +186,7 @@ select = [ "YTT", ] -ignore = ["S105", "S101", "D107", "D105", "PLR0913", "SIM108", "PT001", "A005"] +ignore = ["S105", "S101", "D107", "D105", "PLR0913", "SIM108", "PT001", "A005", "TID252"] fixable = ["I"] unfixable = [] diff --git a/tests/test_iregexp.py b/tests/test_iregexp.py index f1b91e6..b8a27e5 100644 --- a/tests/test_iregexp.py +++ b/tests/test_iregexp.py @@ -1,34 +1,201 @@ import pytest -try: - import iregexp_check # noqa: F401 +from jsonpath._iregexp import check_iregexp - IREGEXP_AVAILABLE = True -except ImportError: - IREGEXP_AVAILABLE = False -import jsonpath - - -@pytest.mark.skipif(IREGEXP_AVAILABLE is False, reason="requires iregexp_check") -def test_iregexp_check() -> None: - # Character classes are OK. - query = "$[?match(@, '[0-9]+')]" - data = ["123", "abc", "abc123"] - assert jsonpath.findall(query, data) == ["123"] - - # Multi character escapes are not. - query = "$[?match(@, '\\\\d+')]" - assert jsonpath.findall(query, data) == [] - - -@pytest.mark.skipif(IREGEXP_AVAILABLE, reason="iregexp_check is available") -def test_no_iregexp_check() -> None: - # Character classes are OK. - query = "$[?match(@, '[0-9]+')]" - data = ["123", "abc", "abc123"] - assert jsonpath.findall(query, data) == ["123"] - - # Multi character escapes are OK when iregexp_check is not installed. - query = "$[?match(@, '\\\\d+')]" - assert jsonpath.findall(query, data) == ["123"] +@pytest.mark.parametrize( + ("pattern", "want"), + [ + (r"a.b", True), + (r"[0-9]", True), + (r"foo|bar", True), + (r"[ab]{3}", True), + (r"[ab]{3,5}", True), + (r"[ab]{3,}", True), + (r"[^ab]", True), + (r"\p{L}", True), + (r"\p{Lu}", True), + (r"\p{Ll}", True), + (r"\p{Lt}", True), + (r"\p{Lm}", True), + (r"\p{Lo}", True), + (r"\p{Mn}", True), + (r"\p{Mc}", True), + (r"\p{Me}", True), + (r"\p{Nd}", True), + (r"\p{Nl}", True), + (r"\p{No}", True), + (r"\p{Pc}", True), + (r"\p{Pd}", True), + (r"\p{Ps}", True), + (r"\p{Pe}", True), + (r"\p{Pi}", True), + (r"\p{Pf}", True), + (r"\p{Po}", True), + (r"\p{Sm}", True), + (r"\p{Sc}", True), + (r"\p{Sk}", True), + (r"\p{So}", True), + (r"\p{Zs}", True), + (r"\p{Zl}", True), + (r"\p{Zp}", True), + (r"\p{Cc}", True), + (r"\p{Cf}", True), + (r"\p{Co}", True), + (r"\p{Cn}", True), + (r"\P{L}", True), + (r"\P{Lu}", True), + (r"\P{Ll}", True), + (r"\P{Lt}", True), + (r"\P{Lm}", True), + (r"\P{Lo}", True), + (r"\P{Mn}", True), + (r"\P{Mc}", True), + (r"\P{Me}", True), + (r"\P{Nd}", True), + (r"\P{Nl}", True), + (r"\P{No}", True), + (r"\P{Pc}", True), + (r"\P{Pd}", True), + (r"\P{Ps}", True), + (r"\P{Pe}", True), + (r"\P{Pi}", True), + (r"\P{Pf}", True), + (r"\P{Po}", True), + (r"\P{Sm}", True), + (r"\P{Sc}", True), + (r"\P{Sk}", True), + (r"\P{So}", True), + (r"\P{Zs}", True), + (r"\P{Zl}", True), + (r"\P{Zp}", True), + (r"\P{Cc}", True), + (r"\P{Cf}", True), + (r"\P{Co}", True), + (r"\P{Cn}", True), + ("a", True), + ("abc", True), + ("cat|dog|fish", True), + ("a|b|c|d|e|f|g", True), + ("", True), + ("a*", True), + ("a+", True), + ("a?", True), + ("a{3}", True), + ("a{2,5}", True), + ("a{0,1}", True), + ("a{10,}", True), + ("(abc)*", True), + ("(foo|bar)+", True), + ("(a?b*c+){2,4}", True), + ("[a-z]", True), + ("[a-zA-Z0-9]", True), + ("[^0-9]", True), + ("[^a-z]", True), + ("[-_.]", True), + ("[\\[\\]\\\\\\^\\-]", True), + ("[a-z0-9._%+-]", True), + (".", True), + ("foo\\.bar", True), + ("\\n\\r\\t", True), + ("\\|\\(\\)\\[\\]\\{\\}\\*\\+\\?\\.\\^\\\\", True), + ("\\p{Lu}+", True), + ("\\p{Ll}*", True), + ("\\p{Nd}{1,4}", True), + ("\\P{Nd}+", True), + ("[\\p{Lu}\\p{Ll}]", True), + ("[^\\p{Nd}]", True), + ("(19|20)[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])", True), # ISO Date + ("([0-9]{1,3}\\.){3}[0-9]{1,3}", True), # Simplified IPv4 + ("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}", True), # Email + ( + "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}", + True, + ), + ("((a|b)+|(c|d)*)?", True), + ("((([a-z])))", True), + (r"(?[a-z]*)", False), + (r"\d", False), + (r"[\S ]", False), + (r"[0-9]*?", False), + (r"(\w)\1", False), + (r"(?=.*[a-z])(?=.*[A-Z])(?=.*)[a-zA-Z]{8,}", False), + (r"(?<=[a-z]{4})\[a-z]{2}", False), + (r"(?:[a-z]+)", False), + (r"(?>[a-z]+)", False), + (r"(?(1)a|b)", False), + (r"(?#comment)", False), + (r"(?i)[a-z]+", False), + ("\\D", False), + ("\\w", False), + ("\\W", False), + ("\\s", False), + ("\\S", False), + ("abc\\ddef", False), + ("[\\d]", False), + ("[a-z\\s0-9]", False), + ("[^]", False), + ("[a-z-_]", False), + ("abc[^]", False), + ("[^]abc", False), + ("[a-z-[aeiou]]", False), + ("[0-9-[5]]", False), + ("(", False), + (")", False), + ("(abc", False), + ("abc)", False), + ("((a|b)", False), + ("(a|b))", False), + (")(", False), + ("[", False), + ("]", False), + ("[a-z", False), + ("a-z]", False), + ("[a-z[b-c]", False), + ("\\", False), + ("abc\\", False), + ("foo\\", False), + ("*", False), + ("+", False), + ("?", False), + ("*abc", False), + ("+abc", False), + ("?abc", False), + ("{2}", False), + ("{2,4}", False), + ("a++", False), + ("a**", False), + ("a??", False), + ("a+*", False), + ("a{2}{3}", False), + ("a{}", False), + ("a{2", False), + ("a{2,4", False), + ("a{abc}", False), + ("a{,5}", False), + ("(?=abc)", False), + ("(?!abc)", False), + ("(?<=abc)", False), + ("(? None: # noqa: FBT001 + assert check_iregexp(pattern) == want diff --git a/tests/test_regex_cache.py b/tests/test_regex_cache.py index c41eedb..681b805 100644 --- a/tests/test_regex_cache.py +++ b/tests/test_regex_cache.py @@ -7,13 +7,6 @@ REGEX_AVAILABLE = False -try: - import iregexp_check # noqa: F401 - - IREGEXP_AVAILABLE = True -except ImportError: - IREGEXP_AVAILABLE = False - import pytest from jsonpath import JSONPathError @@ -35,9 +28,8 @@ def test_malformed_patterns_are_cached() -> None: assert search_func.cache["bc["] is None -@pytest.mark.skipif(IREGEXP_AVAILABLE is False, reason="requires iregexp_check") def test_invalid_iregexp_patterns_are_cached() -> None: - search_func = Search(cache_capacity=2) + search_func = Search(cache_capacity=2, check_iregexp=True) assert len(search_func.cache) == 0 assert search_func("ab123cdef", "\\d+") is False assert len(search_func.cache) == 1 diff --git a/tests/test_set_iregexp_check.py b/tests/test_set_iregexp_check.py new file mode 100644 index 0000000..08dbb2e --- /dev/null +++ b/tests/test_set_iregexp_check.py @@ -0,0 +1,28 @@ +import jsonpath +from jsonpath.function_extensions import Match + + +def test_enable_iregexp_check() -> None: + env = jsonpath.JSONPathEnvironment() + env.function_extensions["match"] = Match(check_iregexp=True) + # Character classes are OK. + query = "$[?match(@, '[0-9]+')]" + data = ["123", "abc", "abc123"] + assert env.findall(query, data) == ["123"] + + # Multi character escapes are not. + query = "$[?match(@, '\\\\d+')]" + assert env.findall(query, data) == [] + + +def test_disable_iregexp_check() -> None: + env = jsonpath.JSONPathEnvironment() + env.function_extensions["match"] = Match(check_iregexp=False) + # Character classes are OK. + query = "$[?match(@, '[0-9]+')]" + data = ["123", "abc", "abc123"] + assert env.findall(query, data) == ["123"] + + # Multi character escapes are OK too. + query = "$[?match(@, '\\\\d+')]" + assert env.findall(query, data) == ["123"]