我什么时候应该使用解析器? [英] When should I use a parser?

查看:83
本文介绍了我什么时候应该使用解析器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Regexes中遇到问题,无法将代码分为功能组件.它们可能会破裂,或者可能需要很长时间才能完成.经验提出了一个问题:

I have had problems in Regexes to divide a code up into functional components. They can break or it can take a long time for them to finish. The experience raises a question:

何时应使用解析器?"

"When should I use a parser?"

推荐答案

当模式可能变化时,如果您对文本的词法或语义含义感兴趣,则应使用解析器.当您只是想匹配或替换字符模式而不论其功能含义如何时,解析器通常都是过大的.

You should use a parser when you are interested in the lexical or semantic meaning of text, when patterns can vary. Parsers are generally overkill when you are simply looking to match or replace patterns of characters, regardless of their functional meaning.

在您的情况下,您似乎对文本(代码的功能组件")背后的含义感兴趣,因此解析器将是更好的选择.但是,解析器可以在内部使用正则表达式,因此不应将它们视为互斥的.

In your case, you seem to be interested in the meaning behind the text ("functional components" of code), so a parser would be the better choice. Parsers can, however, internally make use of regex, so they should not be regarded as mutually exclusive.

但是,解析器"并不自动意味着它必须很复杂.例如,如果您对C代码块感兴趣,则可以简单地解析嵌套的{和}组.该解析器只对两个标记("{"和}")以及它们之间的文本块感兴趣.

A "parser" does not automatically mean it has to be complicated, however. For example, if you are interested in C code blocks, you could simply parse nested groups of { and }. This parser would only be interested in two tokens ('{' and '}') and the blocks of text between them.

但是,由于嵌套的语义,此处简单的正则表达式比较是不够的.输入以下代码:

However, a simple regex comparison is not sufficient here because of the nested semantics. Take the following code:

void Foo(bool Bar)
{
    if(Bar)
    {
        f();
    }
    else
    {
        g();
    }
}

解析器将了解Foo的整体范围以及Foo中包含的每个内部范围(if和else块).当它遇到每个"{"标记时,它理解"了它们的含义.但是,简单的搜索无法理解文字背后的含义,并且可能会将以下内容解释为一个块,我们当然知道这是不正确的:

A parser will understand the overall scope of Foo, as well as each inner scope contained within Foo (the if and else blocks). As it encounters each '{' token, it "understands" their meaning. A simple search, however does not understand the meaning behind the text and may interpret the following to be a block, which we of course know is not correct:

{
    if(Bar)
    {
        f();
    }

这篇关于我什么时候应该使用解析器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆