带括号的数学运算的正则表达式 [英] Regular expression for math operations with parentheses

查看:268
本文介绍了带括号的数学运算的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,我正在尝试编写一个与数学表达式中的单位匹配的正则表达式,即运算符之间的东西

In java, I'm trying to write a regular expression that will match a unit within a mathematical expression, i.e. things that are between operators

我的意思是,在1 + [1 + 2]这样的表达式中,正则表达式应匹配前1,然后是[1 + 2]。

What I mean is, in an expression like 1 + [1 + 2], the regex should match the first 1 and then the [1 + 2].

我所拥有的是* [ ([ - +]?\d +(\.\ + +)?)(\ [。+ \])] *

What I have is *[([-+]?\d+(\.\d+)?)(\[.+\])] *

其中([ - +]?\d +(\.\d +)?)应该匹配任何数字和

Of which ([-+]?\d+(\.\d+)?) is supposed to match any number and

(\ [。+ \])

应该匹配括号内的内容,但是它不起作用......它出于某种原因匹配']'和''之类的东西。

Is supposed to match something inside parentheses, but it isn't working...it's matching things like ']' and ' ' for some reason.

任何帮助都会很棒:)

不幸的是,这是练习的一部分,所以我只能使用基本的java库。 ..它也意味着要用正则表达式练习。我在这里遗漏了一些基本的东西吗?

Unfortunately this is part of an exercise and so I can only use the basic java library...It's also meant to be an exercise in regular expressions. Am I missing something basic here?

推荐答案

您找不到带正则表达式的匹配括号。这是为常规语言提供引理(regexx的数学对象)的结果代表)不持有匹配的开/关parens的语言。

You can't find matching parentheses with regular expressions. This is a consequence of the pumping lemma for regular languages (the mathematical objects that regexes represent) not holding for languages with matched open/close parens.

至少你需要一个无上下文的解析器。这些可以使用ANTLR或JavaCC构建。

You'll need a context-free parser at the least. Those can be built with ANTLR or JavaCC.

这篇关于带括号的数学运算的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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