1

I want to understand, is my expression in brackets. I create such regExp -

public static final String complexValue = "([-]?[(].+[)])"

But I have fail on such input string -

String st = "(4+6)+(3)"

Is there a way to create such regExp, that string (5+x) matches it and string (4+6)+(3) no.

Mary Ryllo
  • 2,321
  • 7
  • 34
  • 53

2 Answers2

2

Literal answer is yes: "^\\(5\\+x\\)$" does what you asked, but not what you want.

The problem is, it's unclear what you want for ((4)+(6)): should it match? Do you want to allow potentially infinite nesting of parentheses, or just a pair of outer parentheses with no inner parentheses allowed?

In the first case, your grammar is irregular, so regular expressions are unable to parse it. (I seem to recall that there are "irregular regular expression" dialects, but IIRC java implementation is not among them).

In the second case, something like "^\\([^)]+\\)$" will do the job.

Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69
  • unfortunately, ((4)+(6)) should match=( thank for your answer. – Mary Ryllo Jan 13 '13 at 15:06
  • So, there is no way, as to count brackets? – Mary Ryllo Jan 13 '13 at 15:08
  • It depends on what else you want to accept or reject, i.e. how much will you tolerate false positives and false negatives. E.g. you can use JEP (a full-featured math expression parser), with an *additional* requirement that a valid expression is within parentheses. Counting brackets is simple, but it won't reject `(4+(6-))`, for example. – Anton Kovalenko Jan 13 '13 at 15:17
  • @Anton “Counting brackets is simple” – in regular expressions? It’s actually impossible. Sure, you can use non-regular extensions to *match* parentheses (but not to count them) but [I wouldn’t call it simple](http://stackoverflow.com/a/6331667/1968). – Konrad Rudolph Jan 13 '13 at 15:25
  • @KonradRudolph I assumed that OP meant "counting brackets manually, in a loop", maybe in addition to regexp match, and doing this (ensuring that the counter never drops to 0) is simple. – Anton Kovalenko Jan 13 '13 at 15:27
0

So you want to match an addition of two numbers surrounded by parentheses? Then the following should work.

^\(\-?\d+\+\-?\d+\)$
pemistahl
  • 9,304
  • 8
  • 45
  • 75