aaa:bbb(123)我正在尝试使用 Pyparsing将字符串拆分为标记。
我可以使用正则表达式来做到这一点,但我需要通过 Pyparsing 来做到这一点。
解决re方案将如下所示:
>>> import re
>>> string = 'aaa:bbb(123)'
>>> regex = '(\S+):(\S+)\((\d+)\)'
>>> re.match(regex, string).groups()
('aaa', 'bbb', '123')
Run Code Online (Sandbox Code Playgroud)
这很清楚也很简单。这里的关键点是\S+“除了空格之外的所有内容”。
现在我将尝试使用 Pyparsing 来做到这一点:
>>> from pyparsing import Word, Suppress, nums, printables
>>> expr = (
... Word(printables, excludeChars=':')
... + Suppress(':')
... + Word(printables, excludeChars='(')
... + Suppress('(')
... + Word(nums)
... + Suppress(')')
... )
>>> expr.parseString(string).asList()
['aaa', 'bbb', '123']
Run Code Online (Sandbox Code Playgroud)
好的,我们得到了相同的结果,但这看起来不太好。我们已经设置excludeChars让 Pyparsing 表达式在我们需要的地方停止,但这看起来并不健壮。如果我们在源字符串中包含“排除”字符,则相同的正则表达式将正常工作:
>>> string = 'a:aa:b(bb(123)'
>>> re.match(regex, string).groups()
('a:aa', 'b(bb', '123')
Run Code Online (Sandbox Code Playgroud)
而 Pyparsing 异常显然会中断:
>>> expr.parseString(string).asList()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/long/path/to/pyparsing.py", line 1111, in parseString
raise exc
ParseException: Expected W:(0123...) (at char 7), (line:1, col:8)
Run Code Online (Sandbox Code Playgroud)
那么,问题是我们如何使用 Pyparsing 实现所需的逻辑?
使用带有前瞻断言的正则表达式:
from pyparsing import Word, Suppress, Regex, nums, printables
expr = (
Word(printables, excludeChars=':')
+ Suppress(':')
+ Regex(r'\S+[^\(](?=\()')
+ Suppress('(')
+ Word(nums)
+ Suppress(')')
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
545 次 |
| 最近记录: |