Roey Golzarpoor Roey Golzarpoor - 1 year ago 167
Java Question

Regex for validating correct input for calculator

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 having 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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download