我需要匹配未定義\w:模式之間的文本(下面的測驗腳本n: text中foo: text的n: text foo: more text更多示例)。
為此,我使用了 pythonfinditer和正則運算式,但我無法在占位符之間捕獲更多的單詞。如何調整正則運算式或finditer方法來做我想做的事?
import re
def test_query_parse_regex(query, expected_result):
result = {}
# perform the matching here, this needs to change
r = r"([\w-] ):\s?([\w-]*)"
matches = re.finditer(r, query)
for match in matches:
# eg 'n'
operator = match.group(1).strip()
# eg 'text'
operator_value = match.group(2).strip()
# build a dict for comparison
result[operator] = operator_value
if result == expected_result:
print(f"PASS: {query}")
else:
print(f"FAIL: {query}")
print(f" Expected: {expected_result}")
print(f" Got : {result}")
checks = [
# Query, expected
("n: tom", {"n": "tom"}),
("n: tom preston", {"n": "tom preston"}),
("n: tom l: london", {"n": "tom", "l": "london"}),
("n: tom preston l: london derry", {"n": "tom preston", "l": "london derry"}),
]
for check in checks:
test_query_parse_regex(*check)
筆記。我已經嘗試過積極的展望,但也無法做到:r"([\w-] ):\s?([\w-]*)(?=\w:)"
uj5u.com熱心網友回復:
您可以使用
r = r"([\w-] ):\s*(.*?)(?=[\w-] :|$)"
r = r"([\w-] ):\s*(.*?)(?=[\w-] :|\Z)"
請注意,如果您的字串可以有換行符,您還需要將re.finditer部分修改為
re.finditer(r, query, re.DOTALL)
請參閱正則運算式演示。\Z如果您使用re.Morre.MULTILINE選項,則首選版本,因為\Z始終匹配字串的末尾。
詳情:
([\w-] )- 第 1 組:一個或多個單詞或連字符:\s*- 一個冒號和任何零個或多個空格(.*?)- 第 2 組:除換行符之外的零個或多個字符(如果re.DOTALL不使用)盡可能少(?=[\w-] :|\Z)- 需要一個或多個單詞或連字符字符后跟冒號或字串結尾的正向前瞻,緊跟在當前位置的右側。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/460134.html
