From e7fb2288ce912dea1426327cb543e9ba2eebce91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=9D=E7=91=AA=E8=B2=93?= Date: Sat, 4 Feb 2023 14:51:09 +0800 Subject: [PATCH] Revised the parse_query_keywords utility to handle the case with an open double quotation mark without its corresponding close double quotation mark. --- src/accounting/utils/query.py | 23 +++++++++++++++++------ tests/test_utils.py | 4 ++-- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/src/accounting/utils/query.py b/src/accounting/utils/query.py index aea01f9..69934b0 100644 --- a/src/accounting/utils/query.py +++ b/src/accounting/utils/query.py @@ -34,11 +34,22 @@ def parse_query_keywords(q: str | None) -> list[str]: if q == "": return [] keywords: list[str] = [] - while q is not None: - m: re.Match = re.match(r"(?:\"([^\"]+)\"|(\S+))(?:\s+(.+)|)$", q) - if m.group(1) is not None: + while True: + m: re.Match + m = re.match(r"\"([^\"]+)\"\s+(.+)$", q) + if m is not None: keywords.append(m.group(1)) - else: - keywords.append(m.group(2)) - q = m.group(3) + q = m.group(2) + continue + m = re.match(r"\"([^\"]+)\"?$", q) + if m is not None: + keywords.append(m.group(1)) + break + m = re.match(r"(\S+)\s+(.+)$", q) + if m is not None: + keywords.append(m.group(1)) + q = m.group(2) + continue + keywords.append(q) + break return keywords diff --git a/tests/test_utils.py b/tests/test_utils.py index 410f3b2..c414204 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -104,10 +104,10 @@ class QueryKeywordParserTestCase(unittest.TestCase): :return: None. """ + self.assertEqual(parse_query_keywords("coffee \"tea cake"), + ["coffee", "tea cake"]) self.assertEqual(parse_query_keywords("coffee te\"a ca\"ke"), ["coffee", "te\"a", "ca\"ke"]) - self.assertEqual(parse_query_keywords("coffee \"tea cake"), - ["coffee", "\"tea", "cake"]) def test_empty(self) -> None: """Tests the empty query.