【问题标题】:How do I best do balanced quoting with Perl's Regexp::Grammars?我如何最好地使用 Perl 的 Regexp::Grammars 进行平衡引用?
【发布时间】:2010-06-15 16:34:20
【问题描述】:

使用 Damian Conway 的 Regexp::Grammars,我正在尝试匹配不同的平衡引用('foo'"foo",但不是 'foo")机制——例如括号、引号、双引号和双美元。这是我目前正在使用的代码。

<token: pair>        \'<literal>\'|\"<literal>\"|\$\$<literal>\$\$
<token: literal>    [\S]+

这通常可以正常工作,让我可以这样说:

<rule: quote>            QUOTE <.as>? <pair>

我的问题是如何修改输出,以排除 pair 令牌的针符号?

{
  '' => 'QUOTE AS \',\'',
  'quote' => {
               '' => 'QUOTE AS \',\'',
               'pair' => {
                           'literal' => ',',
                           '' => '\',\''
                         }
             }
},

在这里,显然不希望在引用和literal 值之间有pair。有没有更好的方法来匹配'foo'"foo"$$foo$$,有时甚至是( foo ),而不必每次都创建一个不必要的pair 令牌?我可以预处理该令牌或将其折叠到上面吗?或者,编写一个完全不需要它的更好的构造?

【问题讨论】:

    标签: regex perl grammar regexp-grammars


    【解决方案1】:

    根据 Damian,答案实际上在文档的 "Manual result distillation" 部分

    The correct answer is to tell your <pair> token
    to pass the result of each <literal> subrule through as its own
    result, using the MATCH=
    alias (see: "Manual result distillation" in the module documentation)  like so:
    
       <token: pair>        \'<MATCH=literal>\' | \"<MATCH=literal>\" |
    \$\$<MATCH=literal>\$\$
    

    文档是这样说的:

    Regexp::Grammars 还提供对蒸馏过程的完全手动控制。如果您使用保留字 MATCH 作为子规则调用的别名 [...] 请注意,在第二种情况下,即使 和 被捕获到结果哈希中,它们也不会返回,因为 MATCH 别名覆盖了正常的“返回结果哈希”语义并仅返回其关联的子规则(即 )产生的内容。

    【讨论】:

      【解决方案2】:

      使用 Damian 的另一个很棒的模块,Text::Balanced

      【讨论】:

      • 如何将它整合到我的 Regexp::Grammars 的其余部分?
      猜你喜欢
      • 2012-07-14
      • 2012-11-13
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多