正确使用 SkipTo

Using SkipTo correctly

我过去使用过 pyparsing,但只用于小任务,这次我想用它来处理更复杂的事情。

我试图跳过一个 VHDL 架构块,它看起来像这样

architecture Behav of Counter is
  ...many statements I'm not interested in at this point...
end architecture;

这是我尝试过的:

import pyparsing as pp
pp_identifier = pp.Regex(r'([a-zA-Z_][\w]*)')('identifier')
def Keyword(matchString):
    'VHDL keywords are caseless and consist only of alphas'
    return pp.Keyword(matchString, identChars=pp.alphas, caseless=True)

pp_architecture = (
    Keyword('architecture')
    + pp_identifier
    + Keyword('of').suppress()
    + pp_identifier
    + Keyword('is').suppress()
    + Keyword('end')
    + Keyword('architecture')
    )

print(pp_architecture.parseString('''
architecture beh of sram is end architecture
''', parseAll=True))

# this works as I expected, it prints
# ['architecture', 'beh', 'sram', 'end', 'architecture']

但是在将 pp_architecture 更改为使用 SkipTo 后,它失败了:

pp_architecture = (
    Keyword('architecture')
    + pp_identifier
    + Keyword('of').suppress()
    + pp_identifier
    + Keyword('is').suppress()
    + pp.SkipTo(Keyword('end') + Keyword('architecture'))
    )

print(pp_architecture.parseString('''
architecture beh of sram is end architecture
''', parseAll=True))
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "C:\Python27\lib\site-packages\pyparsing.py", line 1125, in parseString
    raise exc
pyparsing.ParseException: Expected end of text (at char 29), (line:2, col:29)

我还尝试在 isend 之间添加其他文本(我希望被跳过)以确保 "empty skip" 不是问题,但这并没有也不帮忙。

我做错了什么?

SkipTo 跳到匹配的文本,但默认情况下 解析该文本。所以你将解析位置推进到 'end architecture',但实际上并没有解析它。

您可以:

  1. SkipTo 表达式后添加 Keyword('end') + Keyword('architecture'),或
  2. SkipTo 表达式的构造函数中传递 include=True,告诉它跳到 解析给定的字符串。