PyParsing-匹配字符串,后跟子字符串

时间:2019-02-05 18:19:53

标签: python python-3.x pyparsing

我正在尝试使用PyParsing解析一些自动生成的SQL Server脚本。我无法让解析器停止对GO关键字的解析。

from pyparsing import *

test = '''
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
'''

working = Literal("SET") + Word(printables) * 2
not_working = Literal("SET") + OneOrMore(Word(printables) + ~Literal("GO"))

print('Working')
for result, start, end in working.scanString(test):
    print( "Found {0} at [{1}:{2}]".format(result, start, end))

print('\nNot working')
for result, start, end in not_working.scanString(test):
    print( "Found {0} at [{1}:{2}]".format(result, start, end))

输出如下:

"Working"
Found ['SET', 'ANSI_NULLS', 'ON'] at [1:18]
Found ['SET', 'QUOTED_IDENTIFIER', 'ON'] at [22:46]

"Not working -- missing the ON keyword"
Found ['SET', 'ANSI_NULLS'] at [1:15]
Found ['SET', 'QUOTED_IDENTIFIER'] at [22:43]

由于某种原因,我的“无效”示例未获得ON关键字。解析器看到GO关键字时如何告诉它停止?

0 个答案:

没有答案