Albin I Albin I - 1 month ago 6
Java Question

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

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'm sorry if the question isn't clear.

Answer

I think using of regular expression will be best in your case. You can write something like:

    String input = "100a^atcs";
    Pattern p = Pattern.compile("(\\d+[\\+\\-\\*\\^].*)");
    Matcher m = p.matcher(input);
    if (m.matches())
    {
        //do code...
    }