Albin I Albin I - 1 year ago 63
Java Question

Java - see if input contains only numbers to the left of the operator

I have a problem I can't seem to solve.
I want a piece of code only to run when the input only has numbers on the left side of the operator.
For example:
If the input is 100+, then the code should run.

But also if the input is 100-, 100*, 100/, 100^ etc.

I also want to be able to parse expressions like -100*50.

I'm sorry if the question isn't clear.

Answer Source

This method uses a Regular Expression that matches a line that starts with an optional - sign, an optinal space, then one or more numbers, an optional space, an operator (in this case, +, -, *, / or ^)m an optinal space, an optional - sign, an optinal space, then one or more numbers and finally, optional line endings.

public static void main(String[] args)
    Pattern p = Pattern.compile("^\\-?\\s?\\d+\\s?[\\+\\-*\\/\\^]\\s?\\-?\\s?\\d+\\r?\\n?$");
    System.out.println(p.matcher("123+").matches()); // outputs "true"
    System.out.println(p.matcher("123").matches()); // outputs "false"
    System.out.println(p.matcher("- 123123 *").matches()); // outputs "true"
    System.out.println(p.matcher("- 9843 * 23409").matches()); // outputs "true"

You can also try it online and provide your own input.

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