Revised the parse_query_keywords utility to handle the case with an open double quotation mark without its corresponding close double quotation mark.

This commit is contained in:
依瑪貓 2023-02-04 14:51:09 +08:00
parent 17ba7659b6
commit e7fb2288ce
2 changed files with 19 additions and 8 deletions

View File

@ -34,11 +34,22 @@ def parse_query_keywords(q: str | None) -> list[str]:
if q == "": if q == "":
return [] return []
keywords: list[str] = [] keywords: list[str] = []
while q is not None: while True:
m: re.Match = re.match(r"(?:\"([^\"]+)\"|(\S+))(?:\s+(.+)|)$", q) m: re.Match
if m.group(1) is not None: m = re.match(r"\"([^\"]+)\"\s+(.+)$", q)
if m is not None:
keywords.append(m.group(1)) keywords.append(m.group(1))
else: q = m.group(2)
keywords.append(m.group(2)) continue
q = m.group(3) 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 return keywords

View File

@ -104,10 +104,10 @@ class QueryKeywordParserTestCase(unittest.TestCase):
:return: None. :return: None.
""" """
self.assertEqual(parse_query_keywords("coffee \"tea cake"),
["coffee", "tea cake"])
self.assertEqual(parse_query_keywords("coffee te\"a ca\"ke"), self.assertEqual(parse_query_keywords("coffee te\"a ca\"ke"),
["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: def test_empty(self) -> None:
"""Tests the empty query. """Tests the empty query.