带反斜杠的带引号的字符串,带pyparsing

2024-06-09 13:57:40 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码

text = QuotedString(quoteChar="(", endQuoteChar=")", escChar="\\")
text.leaveWhitespace()

def test_hex_with_backslashN_code(self):
    self.assertEqual(text.parseString("(\x01\x0a)")[0], "(\x01\x0a)")

触发异常:

^{pr2}$

因为“\x0a”hexa值被解释为'\n',即使在leaveWhitespace调用中也不会被视为普通字符。在

我也试过使用skipot,但我没能处理好逃出的内括号,比如:

"( I am \( John \))"

使用解析器

text = "(" + SkipTo(")")

有什么办法解决这个问题吗?在


Tags: 代码texttestselfdefwithhexx01
3条回答

以下是我最终找到的解决方案:

escaped_paren = Literal("\(") | Literal("\)")
text = "(" + SkipTo(")", ignore=escaped_paren)

尝试在字符串前面加上r。如果你有一根绳子

"(\x01\x0a)"

把它改成

^{pr2}$

结果是斜杠被立即解释,而不是到达pyparsing。你有text.parseString("(\x01\x0a)"),它的text.parseString("(\x01\n)")完全相同。在

试试这个解决方案,它解决了kirelagin发现的反斜杠问题:

text = QuotedString(quoteChar="(", endQuoteChar=")", escChar="\\", unquoteResults=False)

print text.parseString(r"(\x01\x0a)")
assert(text.parseString(r"(\x01\x0a)")[0] == r"(\x01\x0a)")

印刷品:

^{pr2}$

因为您假设将包括引号字符,所以添加参数unquoteResults=False。如果您无论如何都要去掉()的,那么不妨让pyparsing为您做这件事,并将此参数作为True传递(或者忽略它,因为True是默认值)。在

相关问题 更多 >