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
What I mean is, in an expression like 1 + [1 + 2], the regex should match the first 1 and then the [1 + 2].
What I have is *[([-+]?\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.
Any help would be great 🙂
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?
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.
You’ll need a context-free parser at the least. Those can be built with ANTLR or JavaCC.