首先,您的v2 表达式实际上是您的v1 表达式的超集。也就是说,任何可以匹配v1 的东西也会匹配v2,所以你真的不需要做value = v1 | v2,value = v2 就可以了。
然后,要处理多个“相邻”引用字符串的情况,而不是解析单个引用字符串,而是解析一个或多个,然后使用解析操作将它们连接起来:
v2 = OneOrMore(QuotedString('"', multiline=True, escQuote='""'))
# add a parse action to convert multiple matched quoted strings to a single
# concatenated string
v2.addParseAction(''.join)
value = v2
# I made a slight change in this expression, moving the results names
# down into this compositional expression
kv = Group(key("key") + eq + value("value"))("key_value")
使用此测试代码:
for parsed_kv in kv.searchString(source):
print(parsed_kv.dump())
print()
将打印:
[['key2', 'value2']]
- key_value: ['key2', 'value2']
- key: 'key2'
- value: 'value2'
[0]:
['key2', 'value2']
- key: 'key2'
- value: 'value2'
[['key3', 'value3 and some more text\n']]
- key_value: ['key3', 'value3 and some more text\n']
- key: 'key3'
- value: 'value3 and some more text\n'
[0]:
['key3', 'value3 and some more text\n']
- key: 'key3'
- value: 'value3 and some more text\n'
[['key4', 'value4 and "inserted quotes" with\nmore text']]
- key_value: ['key4', 'value4 and "inserted quotes" with\nmore text']
- key: 'key4'
- value: 'value4 and "inserted quotes" with\nmore text'
[0]:
['key4', 'value4 and "inserted quotes" with\nmore text']
- key: 'key4'
- value: 'value4 and "inserted quotes" with\nmore text'
[['key5', 'some more text that is so long that the authors who serialized it to a file thought it would be a good idea to to concatenate strings this way']]
- key_value: ['key5', 'some more text that is so long that the authors who serialized it to a file thought it would be a good idea to to concatenate strings this way']
- key: 'key5'
- value: 'some more text that is so long that the authors who serialized it to a file thought it would be a good idea to to concatenate strings this way'
[0]:
['key5', 'some more text that is so long that the authors who serialized it to a file thought it would be a good idea to to concatenate strings this way']
- key: 'key5'
- value: 'some more text that is so long that the authors who serialized it to a file thought it would be a good idea to to concatenate strings this way'