草庐IT

php - 编写一个简单的语法分析器

coder 2024-04-13 原文

这是我想做的 - 在 Php 中:给定一个字符串,得到如下结果:

  • (a()?b|c) a 是一个返回 true 或 false 的函数。这应该在调用 a()
  • 后给出 bc
  • (a()?(b()?d|e)|c)。同理。最后的结果应该是d, e 或者c
  • (a()?(b()?d|e)|(c()?f|g))。同理。最终结果应该是d, e, f or g

我面临的问题是 a(在我之前的示例中)也可以是表达式,如下所示:

((h() ? a | i) ? (b() ? d | e) | (c() ? f | g))

我正在尝试使用正则表达式来执行此操作,但这不起作用。

$res=preg_match_all('/\([^.\(]+\)/', $str, $matches);

所以最后我想像这样调用我的函数:

$final_string=compute("(a(x(y(z()?o|p)))?(b()?d|e)|(c()?f|g))");

$final_string中的最终结果应该是d, e, f or g

我很确定以前做过一些事情,但无法在谷歌上找到它。 你会怎么做?

更准确地说,这是我希望分析字符串的方式:

$str =
    "
    (myfunction(12684444)
    ?   {* comment *}
        (
            myfunction(1)|
            myfunction(2)|
            myfunction(80)|
            myfunction(120)|
            myfunction(184)|
            myfunction(196)
        ?   {* comment *}
            AAAAA
            {* /comment *}
        |
            {* Ignore all other values: *}
            BBBBB
        ) {* /comment *}

    |   {* comment *}
        CCCC
    )";

最佳答案

我相信您正在寻找这样的东西。一路穿插解释。

如果您打算将语法扩展到远远超出您已有的范围(实际上即使您还没有),请编写一个合适的解析器,而不是尝试在一个正则表达式中完成所有事情。这是一个有趣的练习,展示了 PCRE 的一些强大功能,但它很容易变得无法维护。


测试字符串:

$tests = [
    "a",
    "a()",
    "a(b)",
    "(a?b|c)",
    "(a()?(b()?d|e)|(c()?f|g))",
    "((h() ? a | i) ? (b() ? d | e) | (c() ? f | g))",
    "(a(d(f))?b(e(f))|c)"
];

供以后使用。


正则表达式:

$regex = <<<'REGEX'
/
(?(DEFINE)
    # An expression is any function, ternary, or string.
    (?<expression>
        (?&function) | (?&ternary) | (?&string)
    )
)

^(?<expr>

    # A function is a function name (consisting of one or more word characters)
    # followed by an opening parenthesis, an optional parameter (expression),
    # and a closing parenthesis.
    # Optional space is allowed around the parentheses.
    (?<function>
        (?<func_name> \w+ )
        \s*\(\s*
        (?<parameter> (?&expression)? )
        \s*\)\s*
    )

    |

    # A ternary is an opening parenthesis followed by an 'if' expression,
    # a question mark, an expression evaluated when the 'if' is true,
    # a pipe, an expression evaluated when the 'if' is false, and a closing
    # parenthesis.
    # Whitespace is allowed after '('; surrounding '?' and '|'; and before ')'.
    (?<ternary>
        \(\s*
        (?<if> (?&expression) )
        \s*\?\s*
        (?<true> (?&expression) )
        \s*\|\s*
        (?<false> (?&expression) )
        \s*\)
    )

    |

    # A string, for simplicity's sake here, we'll call a sequence of word
    # characters.
    (?<string> \w+ )
)$
/x
REGEX;

自由使用命名捕获组有很大帮助,x (PCRE_EXTENDED) 修饰符允许注释和空格也是如此。 (?(DEFINE)...) block 允许您定义仅供引用使用的子模式。


正则表达式演示:

foreach ($tests as $test) {
    if (preg_match($regex, $test, $m)) {
        echo "expression: $m[expr]\n";

        if ($m['function']) {
            echo "function: $m[function]\n",
                 "function name: $m[func_name]\n",
                 "parameter: $m[parameter]\n";
        } elseif ($m['ternary']) {
            echo "ternary: $m[ternary]\n",
                 "if: $m[if]\n",
                 "true: $m[true]\n",
                 "false: $m[false]\n";
        } else {
            echo "string: $m[string]\n";
        }

        echo "\n";
    }
}

输出:

expression: a
string: a

expression: a()
function: a()
function name: a
parameter: 

expression: a(b)
function: a(b)
function name: a
parameter: b

expression: (a?b|c)
ternary: (a?b|c)
if: a
true: b
false: c

expression: (a()?(b()?d|e)|(c()?f|g))
ternary: (a()?(b()?d|e)|(c()?f|g))
if: a()
true: (b()?d|e)
false: (c()?f|g)

expression: ((h() ? a | i) ? (b() ? d | e) | (c() ? f | g))
ternary: ((h() ? a | i) ? (b() ? d | e) | (c() ? f | g))
if: (h() ? a | i)
true: (b() ? d | e)
false: (c() ? f | g)

expression: (a(d(f))?b(e(f))|c)
ternary: (a(d(f))?b(e(f))|c)
if: a(d(f))
true: b(e(f))
false: c

有点冗长,但足以说明什么是匹配的。


示例 compute() 函数:

function compute($expr) {
    $regex = '/.../x'; // regex from above
    if (!preg_match($regex, $expr, $m)) {
        return false;
    }

    if ($m['function']) {
        if ($m['parameter']) {
            return $m['func_name'](compute($m['parameter']));
        } else {
            return $m['func_name']();
        }
    }

    if ($m['ternary']) {
        return compute($m['if']) ? compute($m['true']) : compute($m['false']);
    }

    return $m['string'];
}

非常简单——执行匹配的函数,评估匹配的三元表达式,或返回匹配的字符串;在适当的地方递归。


compute() 演示:

function a() {return true;}
function b() {return false;}
function d() {return true;}
function e() {return false;}
function h() {return true;}

foreach ($tests as $test) {
    $result = compute($test);
    echo "$test returns: ";
    var_dump($result);
}

输出:

a returns: string(1) "a"
a() returns: bool(true)
a(b) returns: bool(true)
(a?b|c) returns: string(1) "b"
(a()?(b()?d|e)|(c()?f|g)) returns: string(1) "e"
((h() ? a | i) ? (b() ? d | e) | (c() ? f | g)) returns: string(1) "e"
(a(d(f))?b(e(f))|c) returns: bool(false)

我很确定这是正确的。

关于php - 编写一个简单的语法分析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27462254/

有关php - 编写一个简单的语法分析器的更多相关文章

  1. ruby - 树顶语法无限循环 - 2

    我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He

  2. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  3. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  4. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  5. ruby - 在 Ruby 中编写命令行实用程序 - 2

    我想用ruby​​编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序

  6. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  7. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  8. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  9. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  10. ruby-on-rails - Rails - 从另一个模型中创建一个模型的实例 - 2

    我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案

随机推荐