Skip to main content
 首页 » 编程设计

python之意外的 pyparsing 行为

2025年05月04日14artech

我在尝试调试 pyparsing 代码时遇到了这种意外行为:

string1 = "this is a test string : that behaves as I expect\n" 
string2 = "this string does not behave as I expect\n" 
 
field = CharsNotIn(":\n") 
line = field + ZeroOrMore(Literal(":") + field) + LineEnd() 
 
print line.parseString(string1) 
print line.parseString(string2) 

这会产生以下输出:

['this is a test string ', ':', ' that behaves as I expect', '\n'] 
['this string does not behave as I expect'] 

出于某种原因,解析器能够在 string1 中提取行尾字符,但无法在 string2 中提取它。我什至不明白如果它没有找到行尾,它是如何为 string2 生成匹配项的。

这种行为似乎特别适用于行尾字符,因为使用行尾字符以外的字符似乎工作正常:

string1 = "this is a test string : that behaves as I expect*" 
string2 = "this string also behaves as I expect*" 
 
field = CharsNotIn(":*") 
line = field + ZeroOrMore(Literal(":") + field) + Literal("*") 
 
print line.parseString(string1) 
print line.parseString(string2) 

这会产生:

['this is a test string ', ':', ' that behaves as I expect', '*'] 
['this string also behaves as I expect', '*'] 

请您参考如下方法:

打印行以查看它匹配的伪正则表达式。

>>> print line 
{!W:(: 
) [{":" !W:(: 
)}]... LineEnd} 

如果我理解正确,它正在寻找非冒号非换行符,它在第一个换行符处停止(在您的示例 string2 中,它占用整行),然后查找冒号和更多单词,如果它们存在(他们没有),然后是换行符。我的猜测是换行符实例以某种方式被丢弃,而不是你断言如果它不能匹配换行符它就不会匹配字符串是错误的。

>>> print line.parseString('xyzyy') 
['xyzyy'] 

这确实留下了一个问题,为什么即使没有换行符它也匹配......