使用PetitParser在Smalltalk字符串中查找标记

时间:2011-10-18 07:15:10

标签: parsing smalltalk petitparser

我想解析

'This,is,an,example,text'

就像在findTokens中一样

'This,is,an,example,text' findTokens: $, 
an OrderedCollection('This' 'is' 'an' 'example' 'text')

但无法弄清楚怎么用PetitParser,delimitedBy:和separatedBy:没有帮助我,我尝试了

( #any asParser delimitedBy: $, asParser ) plus flatten parse:  'This,is,an,example,text'

但显然没有用

4 个答案:

答案 0 :(得分:3)

您可以将delimitedBy:withoutSeparators结合使用:

|text parser|

text := 'This,is,an,example,text'.
parser := (#word asParser plus flatten delimitedBy: ($, asParser)) withoutSeparators.

parser parse: text

似乎是最近对PetitParser的改进。

答案 1 :(得分:2)

a #delimitedBy: b扩展为a , (b , a) star,因此你的解析器就是说“给我一个用逗号分隔的字符”。

它不是很易读,但这可以满足您的需求:

((($, asParser not , #any asParser) ==> [:nodes | nodes second])
  plus flatten delimitedBy: $, asParser

第一个句子说“解析任何不是逗号的东西”。因此,'12,24'给出了#('12' $, '24')

答案 2 :(得分:1)

尝试

(#word asParser plus flatten separatedBy: $, asParser) 
     ==> [:nodes| nodes copyWithout: $, ]

我希望我理解你想要的东西

答案 3 :(得分:1)

当我想要排除某些东西时,我一直使用PetitParser这种模式。只需定义“我正在寻找的东西”或“我想要排除的东西”(以较易于描述的方式)作为解析器,然后否定它,并根据需要进行处理。

s := 'This,is,an,example,text'.
separator := $, asParser ==> [ :n | nil ].
token := separator negate plus flatten.
p := (token separatedBy: separator) ==> [ :nodes |
    nodes copyWithout: nil ].
p parse: s.
相关问题