Python Pyparsing:检测具有特定结尾的令牌

Python Pyparsing:检测具有特定结尾的令牌,python,pyparsing,Python,Pyparsing,我不知道我在这里做错了什么。也许有人能给我一个关于这个问题的提示。 我想使用pyparsing检测以字符串\u Init终止的某些令牌 例如,我在text one two_Init threeInit four_foo_Init five_foo_bar_Init 我想提取以下行: two_Init four_foo_Init five_foo_bar_Init import pyparsing as pp ident = pp.Word(pp.alphas, pp.a

我不知道我在这里做错了什么。也许有人能给我一个关于这个问题的提示。 我想使用pyparsing检测以字符串
\u Init
终止的某些令牌

例如,我在
text

one
two_Init
threeInit
four_foo_Init
five_foo_bar_Init 
我想提取以下行:

two_Init
four_foo_Init
five_foo_bar_Init 
    import pyparsing as pp

    ident = pp.Word(pp.alphas, pp.alphanums + "_")
    ident_init = pp.Combine(ident + pp.Literal("_Init"))

    for detected, s, e in ident_init.scanString(text): 
        print detected
目前,我已将问题归结为以下几行:

two_Init
four_foo_Init
five_foo_bar_Init 
    import pyparsing as pp

    ident = pp.Word(pp.alphas, pp.alphanums + "_")
    ident_init = pp.Combine(ident + pp.Literal("_Init"))

    for detected, s, e in ident_init.scanString(text): 
        print detected
使用此代码没有结果。如果我删除
Word
语句中的
“\uu
,那么我至少可以检测到两端有
\u Init
的行。但结果并不完全:

['two_Init']
['foo_Init']
['bar_Init']

有人知道我在这里犯了什么大错吗?

问题是,只要不是终止“
\u Init
”中的“
\u
”,您就要接受“
\u
”。这里有两个pyparsing解决方案,一个是更“纯”的pyparsing,另一个只是简单地说了一下,并使用了一个嵌入式正则表达式

samples = """\
one
two_Init
threeInit
four_foo_Init
six_seven_Init_eight_Init
five_foo_bar_Init"""


from pyparsing import Combine, OneOrMore, Word, alphas, alphanums, Literal, WordEnd, Regex

# implement explicit lookahead: allow '_' as part of your Combined OneOrMore, 
# as long as it is not followed by "Init" and the end of the word
option1 = Combine(OneOrMore(Word(alphas,alphanums) | 
                            '_' + ~(Literal("Init")+WordEnd())) 
                  + "_Init")

# sometimes regular expressions and their implicit lookahead/backtracking do 
# make things easier
option2 = Regex(r'\b[a-zA-Z_][a-zA-Z0-9_]*_Init\b')

for expr in (option1, option2):
    print '\n'.join(t[0] for t in expr.searchString(samples))
    print
两个选项均打印:

two_Init
four_foo_Init
six_seven_Init_eight_Init
five_foo_bar_Init