ruby - 树顶基本解析和正则表达式使用

标签 ruby regex parsing treetop

我正在使用 ruby​​ Treetop 库开发一个脚本,但在使用其正则表达式语法时遇到了问题。首先,许多在其他设置中工作的正则表达式在 treetop 上的工作方式不同。

这是我的语法:(myline.treetop)

grammar MyLine
    rule line
        string whitespace condition
    end
    rule string
        [\S]*
    end
    rule whitespace
        [\s]*
    end
    rule condition
        "new" / "old" / "used"
    end
end

这是我的用法:(usage.rb)

require 'rubygems'
require 'treetop'
require 'polyglot'
require 'myline'

parser = MyLineParser.new
p parser.parse("randomstring new")

这肯定会找到新词,而且确实如此!现在我不会扩展它,以便它可以在输入字符串变为“randomstring anotherstring new yetanother and another”时找到新的 并且在规则条件的正则表达式前后可能有任意数量的字符串,后跟空格(包括制表符)。换句话说,如果我向它传递任何包含“new”等单词的句子,它应该能够匹配它。

假设我将语法更改为:

rule line
    string whitespace condition whitespace string
end

然后,它应该能够找到匹配项:

p parser.parse("randomstring new anotherstring")

那么,我需要做什么才能让字符串空白在条件前后重复出现?如果我尝试这样写:

rule line
    (string whitespace)* condition (whitespace string)*
end

,它进入无限循环。如果我用 [] 替换上面的 (),它返回 nil 一般来说,当我使用上面的正则表达式时,正则表达式会返回一个匹配项,但树顶正则表达式不会。 有没有人对如何去做有任何提示/要点?另外,由于树顶的文档不多,而且示例要么太琐碎要么太复杂,有没有人知道更详尽的树顶文档/指南?

最佳答案

看起来您甚至不需要语法来完成您的要求。在这种情况下,一个简单的正则表达式就足够了:

line.match(/(.*)\s(new|old|used)\s(.*)/)

(示例:http://rubular.com/r/Kl8rUifxeu)

你可以得到一个包含条件前后的内容的数组:

Regexp.last_match(1).split + Regexp.last_match(3)

并测试条件:

return "Sweet, it's new!" if Regexp.last_match(2) == "new"

关于ruby - 树顶基本解析和正则表达式使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2404518/

相关文章:

Ruby 元类疯狂

ruby-on-rails - 无法在 Windows 7 中安装 Rails - 意外的文件结束错误

ruby-on-rails - Rails 5 - Shrine 问题 : "undefined method ` cached_image_data' for nil:NilClass"

ruby - 使用 Watir-webdriver : Getting the text of h1 tag

xml - 阻止 Scala 解析 XML

powershell - 在PowerShell中解析 'query user'的更简单方法

java - 忽略在正则表达式中创建单词的开头

regex - Nginx 对变量的字符串操作

regex - 在正则表达式中使用变量

c++ - 使用 Bison/Antlr/Packrat/Elkhound/编写的 LLVM JIT 解析器