1

I need to have some Calculator done, currently i'm dealing with the issue that I need to have only numbers (0,1,2,3,4,5,6,7,8,9) and operators (+, -, *, /, .) in my JTextField which is the user's input.

Currently my regex is like: String REGEX = "^[0-9]+[.]?[0-9]{0,1}$"; and it's from an example that I found over the web.

How do I have also to possibility to allow these operators: +, -, *, /? (the dot is already done)

The total idea is to have it like the Windows Calculator.
I'm not that strong in this topic, please advice.

EDIT: it also needs to have round braces like ( and )

roeygol
  • 4,908
  • 9
  • 51
  • 88

3 Answers3

4

Here's an example that matches your requirements:

^[\d\+\/\*\.\- \(\)]*$

As a JAVA String this would be:

String regex = "^[\\d\\+\\/\\*\\.\\- \\(\\)]*$";

Note that I also added a SPACE to this list of allowed chars.

jHilscher
  • 1,810
  • 2
  • 25
  • 29
  • Can you please have also the numbers inside it ? – roeygol Jan 28 '15 at 17:59
  • I guess, this also validates non-sense expressions like `12.23/`, or `*()`. Maybe is ok to @RoeyGolzarpoor – Albert Jan 28 '15 at 18:00
  • \d is a representation for all numbers. Since chars like '+' also have a meaning in regex, you need to escape them. Java then needs to escape '\' as well. – jHilscher Jan 28 '15 at 18:00
  • @Albert This is true. But dealing with all the possible input constellations would be over the top for a regex. This regex more or less deals only with the set of chars you put into that field. – jHilscher Jan 28 '15 at 18:03
  • @jHilscher. Yeah! You are right. I've been trying, but I didn't succeed ;) – Albert Jan 28 '15 at 18:04
  • Agree with jHilscher, if you want to go further write a function that validates the input. Interesting ideas are found [here](http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form). – Josue Montano Jan 28 '15 at 18:06
  • Most of these escapes are superfluous, `^[\\d+*/.()-]+$` is enough and much more readable. – Toto Jan 28 '15 at 18:26
2

Just in case somebody will need a bit more proper solution:

^(\d+[\+\-\*\/]{1})+\d+$

It is better because these strings won't pass:

45++6*6
12+4+
+2-6

You can test it here: https://regex101.com/r/zB7vV3/2

streetturtle
  • 5,472
  • 2
  • 25
  • 43
0

my regex

^[\d\(]+[\d\+\-\*\/\(\)]+[\d\)]+$

passed:

  • 3+3*5*(2+1)

not good yet:

  • 1+2)
  • 1+)
Miao1007
  • 944
  • 6
  • 22