我正在尝试使用pyparsing来匹配多行字符串,该字符串可以以类似于python的方式继续:
Test = "This is a long " \
"string"
我无法找到让pyparsing认识到这一点的方法。这是我到目前为止所尝试的:
import pyparsing as pp
src1 = '''
Test("This is a long string")
'''
src2 = '''
Test("This is a long " \
"string")
'''
_lp = pp.Suppress('(')
_rp = pp.Suppress(')')
_str = pp.QuotedString('"', multiline=True, unquoteResults=False)
func = pp.Word(pp.alphas)
function = func + _lp + _str + _rp
print src1
print function.parseString(src1)
print '-------------------------'
print src2
print function.parseString(src2)
答案 0 :(得分:5)
问题在于,使用多行引用字符串并不符合您的想法。多行引用字符串实际上就是 - 一个包含换行符的字符串:
import pyparsing as pp
src0 = '''
"Hello
World
Goodbye and go"
'''
pat = pp.QuotedString('"', multiline=True)
print pat.parseString(src0)
解析此字符串的输出为['Hello\n World\n Goodbye and go']
。
据我所知,如果你想要一个类似于Python字符串行为的字符串,你必须自己定义:
import pyparsing as pp
src1 = '''
Test("This is a long string")
'''
src2 = '''
Test("This is a long"
"string")
'''
src3 = '''
Test("This is a long" \\
"string")
'''
_lp = pp.Suppress('(')
_rp = pp.Suppress(')')
_str = pp.QuotedString('"')
_slash = pp.Suppress(pp.Optional("\\"))
_multiline_str = pp.Combine(pp.OneOrMore(_str + _slash), adjacent=False)
func = pp.Word(pp.alphas)
function = func + _lp + _multiline_str + _rp
print src1
print function.parseString(src1)
print '-------------------------'
print src2
print function.parseString(src2)
print '-------------------------'
print src3
print function.parseString(src3)
这会产生以下输出:
Test("This is a long string")
['Test', 'This is a long string']
-------------------------
Test("This is a long"
"string")
['Test', 'This is a longstring']
-------------------------
Test("This is a long" \
"string")
['Test', 'This is a longstring']
注意:Combine
类将各种引用的字符串合并为一个单元,以便它们在输出列表中显示为单个字符串。反斜杠被抑制的原因是它没有被组合成输出字符串的一部分。