Is there a "startswith" method in pyparsing
Hey I have written a very simple parser with pyparsing which detects some tokens in a text and then replaces them with a different string. The problem is that right now my code only works with exact matches. What I'd like to 开发者_如何转开发do is detect partial matches too. For example if the token is "foobar" I'd like to match a word like "foobarfoo". Is there a way to do that with pyparsing? I have looked at the examples and did some research but I came up with nothing.
Thanks
EDIT:
I have a list of tokens to match and a list of words in the text. So I want a solution which takes into account this fact. The list of tokens can be quite big.
Literal('foobar')+Word(pyp.alphas)
defines a pyparsing ParseExpression which requires the text to startwith 'foobar'
followed by any alphacharacter. For example:
import pyparsing as pyp
ident = pyp.Combine(pyp.Literal('foobar')+pyp.Word(pyp.alphas))('foo')
for match in ident.searchString('bar foobarfoo bar foobarbafoo'):
print(match.foo)
yields
foobarfoo
foobarbafoo
Simplest would be to use a pyparsing Regex expression in your grammar:
startsWithFoobar = Regex(r"foobar[a-zA-Z0-9_]+")
精彩评论