如何用pyparsing解析这个字符串

时间:2014-04-09 20:49:16

标签: python regex pyparsing

我可以使用以下正则表达式代码解析my_str:

([\w\s]*)\s(\w+)

但我想使用pyparsing。

我该怎么做?

my_str = "aa234"
expected_result = ["aa234", ""]

my_str = "aa234 bbb2b ccc ddd eee"
expected_result = ["aa234 bbb2b ccc ddd", "eee"]


my_str = "aa234 bbb2b ccc ddd eee fff ggg hhh"
expected_result = ["aa234 bbb2b ccc ddd eee fff ggg", "hhh"]

1 个答案:

答案 0 :(得分:2)

以下是您的示例解析器:

from pyparsing import *

stringWord = Word(alphas, alphanums)

# only want words not at the end of the string for the leading part
leadingWord = stringWord + ~LineEnd()

leadingPart = originalTextFor(stringWord + ZeroOrMore(leadingWord))

# define parser, with named results, similar to named groups in a regex
parser = leadingPart("first") + Optional(stringWord, default='')("second")

以下是它在实践中的运作方式:

tests = ["aa234", 
         "aa234 bbb2b ccc ddd eee ",]
for test in tests:
    results = parser.parseString(test)
    print results.dump()
    print results.first
    print results.second

打印:

['aa234', '']
- first: aa234
- second: 
aa234

['aa234 bbb2b ccc ddd', 'eee']
- first: aa234 bbb2b ccc ddd
- second: eee
aa234 bbb2b ccc ddd
eee