gpt4 book ai didi

ruby - Parslet 中是否提供反向引用?

转载 作者:太空宇宙 更新时间:2023-11-03 18:19:27 24 4
gpt4 key购买 nike

有没有一种方法可以类似于典型正则表达式中的 \1 功能来反向引用 parslet 中的前一个字符串?

我想提取 block 中的字符,例如:

Marker SomeName
some random text, numbers123
and symbols !#%
SomeName

其中“Marker”是一个已知字符串,但“SomeName”是未知的,所以我相信我需要这样的东西:

rule(:name) { ( match('\w') >> match('\w\d') ).repeat(1) } 
rule(:text_within_the_block) {
str('Marker') >> name >> any.repeat.as(:text_block) >> backreference_to_name
}

我不知道如何使用 Parslet 和/或 Ruby 语言编写 backreference_to_name 规则。

最佳答案

来自 http://kschiess.github.io/parslet/parser.html

Capturing input

Sometimes a parser needs to match against something that was already matched against. Think about Ruby heredocs for example:

  str = <-HERE
This is part of the heredoc.
HERE

The key to matching this kind of document is to capture part of the input first and then construct the rest of the parser based on the captured part. This is what it looks like in its simplest form:

  match['ab'].capture(:capt) >>               # create the capture
dynamic { |s,c| str(c.captures[:capt]) } # and match using the capture

这里的关键是 dynamic block 返回一个惰性解析器。它仅在使用时进行评估,并在执行时传递当前上下文以供引用。

-- 更新:添加一个有效的例子 --

所以对于你的例子:

require 'parslet'    
require 'parslet/convenience'

class Mini < Parslet::Parser
rule(:name) { match("[a-zA-Z]") >> match('\\w').repeat }
rule(:text_within_the_block) {
str('Marker ') >>
name.capture(:namez).as(:name) >>
str(" ") >>
dynamic { |_,scope|
(str(scope.captures[:namez]).absent? >> any).repeat
}.as(:text_block) >>
dynamic { |src,scope| str(scope.captures[:namez]) }
}

root (:text_within_the_block)
end
puts Mini.new.parse_with_debug("Marker BOB some text BOB") .inspect
#=> {:name=>"BOB"@7, :text_block=>"some text "@11}

这需要进行一些更改。

  • 我更改了 rule(:name) 以匹配单个单词并添加了 str("") 以检测该单词是否已结束。 (注意:\w 是 [A-Za-z0-9_] 的缩写,因此它包含数字)
  • 我将“任何”匹配更改为以文本不是 :name 文本为条件。 (否则它会消耗 'BOB' 然后无法匹配,即它是贪婪的!)

关于ruby - Parslet 中是否提供反向引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21022363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com