我正在玩 parslet。这是一个简单的解析器,它向我展示了一些不明显的行为。
require 'parslet'
class Parser < Parslet::Parser
rule(:quote) { str('"') }
rule(:escape_char) { str('\\') }
def quoted(term)
quote >> term >> quote
end
rule(:string) {
quoted( (escape_char >> any | quote.absent? >> any).repeat.as(:string) )
}
end
显然,它应该解析双引号字符串。确实如此。但是下面的结果对我来说似乎很奇怪。
Parser.new.string.parse '""'
此代码返回 {:string=>[]}
。为什么 empty array
那里没有 empty string
?我错过了什么?
我正在使用 ruby 2.1.1
和 parslet 1.6.1
最佳答案
长话短说; - 通常,应用于 repeat
的 Parslet 的 as
会捕获一组匹配项;除了在所有匹配项都是原始字符串的特殊情况下,在这种情况下它将连接它们并返回结果字符串。
在您的代码中,repeat
不知道它将捕获的类型,因为没有任何类型,因此它返回空数组。
在这个例子中……空数组似乎是正确的选择。
require 'parslet'
class Parser < Parslet::Parser
rule(:quote) { str('"') }
rule(:escape_char) { str('\\') }
def quoted(term)
quote >> term >> quote
end
rule(:string) {
quoted( (escape_char >> any | quote.absent? >> any).as(:char).repeat.as(:string) )
}
end
puts Parser.new.string.parse('""').inspect # => {:string=>[]}
puts Parser.new.string.parse('"test"').inspect
# => {:string=>[{:char=>"t"@1}, {:char=>"e"@2}, {:char=>"s"@3}, {:char=>"t"@4}]}
当子节点只是字符串时,Parslet 连接成一个字符串。当集合中没有元素时,它默认为空集合而不是空字符串。
也许
是不同的。
来自 http://kschiess.github.io/parslet/parser.html # 重复及其特例
These all map to Parslet::Atoms::Repetition. Please note this little twist to #maybe:
str('foo').maybe.as(:f).parse('') # => {:f=>nil}
str('foo').repeat(0,1).as(:f).parse('') # => {:f=>[]} The‘nil’-value of #maybe is nil. This is catering to the intuition that foo.maybe either gives me foo or nothing at all, not an empty array. But have it your way!
关于ruby - 为什么 Parslet(在 Ruby 中)在解析空字符串文字时返回一个空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25732556/