-1

我在理解正则表达式出了什么问题时遇到了很大的麻烦。为了完整起见,我将列出一些背景信息。

这个程序应该实现一个 SIMPLESEM 解释器。这里关注的语法是这样的:

< Expr >    ==>   < Term > {( + | - ) < Term >}

< Term >    ==>   < Factor > {( * | / | % ) < Factor >}

< Factor >  ==>   < Number > | D[< Expr >] | (< Expr >)

< Number >  ==>   0 | (1..9){0..9}

我得到了这段代码,它应该给我 a 方括号内的内容< Factor >,但它没有用:

 Matcher m;

(m = Pattern.compile("D\\[(.*)").matcher(expr)).find();
        expr = parseExpr(m.group(1));
        (m = Pattern.compile("\\](.*)").matcher(expr)).find();
        expr = m.group(1);

作为示例输入,我有这个:

jumpt 5, D[0] == 0

这里< Factor >关心的是D[0]。它不起作用,因为上面的函数0]parseExpr()处理左括号,它不应该处理。所以我把它改成:

(m = Pattern.compile("D\\[(.*)").matcher(expr)).find();
        expr = m.group(1);
        (m = Pattern.compile("\\](.*)").matcher(expr)).find();
        expr = parseExpr(m.group(1));

但由于匹配器/正则表达式,这不起作用。我相信它输出了一个空字符串。所以然后我尝试了这个,它只是给了我一个没有匹配的错误:

(m = Pattern.compile("D\\[(.*)").matcher(expr)).find();
expr = m.group(1);

if(expr.contains("(.*)")) 
{
    (m = Pattern.compile("\\](.*)").matcher(expr)).find();
}
else
{
    (m = Pattern.compile("\\]").matcher(expr)).find();
}   
    expr = m.group(1);
    expr = parseExpr(expr);

它在倒数第二行给出超出范围的索引。在此先感谢您的帮助。

4

2 回答 2

0

If you want the data inside of the square brackets then your regex should look something like:

D\[([^\]]*)

which basically says "Take 'D[', then take everything from there on that isn't a ']' and store it in the match".

Check out Regexper to obtain a visualization of your regular expressions.

于 2013-01-27T21:18:50.483 回答
0

There is this part D[ <Expr> ] and ( <Expr> ), which introduces the problem of bracket matching. This is not something Java regex can handle, since it doesn't support recursive regex.

In this case, regex is only useful for lexing, you need to write a custom parser for your language.

于 2013-01-27T21:20:16.500 回答