1

I am making a validator...It will get a string and validate it. I want to make that if minus is in the starting of a number it be considered true.Like (-34+56) and (23*-43) will be ok but (23+*23-) will be not ok...Actually it is for a calculator so it should be a proper equation

I tried adding a line that would match - but it didn't work nor It was sensible.

This is my validate method

 public boolean validateInput(String input) {
        if(input.contains(".")) {
            return true;
        }

        Pattern pattern = Pattern.compile("[-]");
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            return true;
        }

        if((input.replaceAll("[^(]","" ).length() != input.replaceAll("[^)]", "").length()) || input.split("[^\\d]").length == 0 || input.length() == 0)
            return false;

//           [\d|-][(|)]   [\d|)][(|\d]|[^\d|(][)|^\d]
//        [\d][(]|[)][\d]|[^\d][)]|[(][^\d]

//        String ope = "*\\/+^-";
        //to check input like 9(, )9, *),(*..
        pattern = Pattern.compile("(\\d\\()|(\\)\\d)|(\\([*\\/+^])|([*\\/+^]\\))");
        matcher = pattern.matcher(input);
        if (matcher.find()) {
            return false;
        }

        //
        pattern = pattern.compile("[^\\d|+*^()\\/]");
        matcher = pattern.matcher(input);
        if (matcher.find()) {
            return false;
        }


        //to check if 2 consecutive operators are there...
        pattern = pattern.compile("[*-+^\\/]{2}");
        matcher = pattern.matcher(input);
        if (matcher.find()) {
            return false;
        }



        return true;
    }

It just gave the error What should be the regex to fix it.

2 Answers2

4

You are approaching this the wrong way.

You need a parser that understands numerical expressions. And regular expressions won't do here. And even if it would: look at the regex you already put up. Do you think you will understand that in 2 months from now, heck in 2 weeks from now?

Thus, the real answer here: forget about regular expressions. Learn how to parse such strings. You can start at the answers given here for guidance.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

I am sorry if I am missing something in your question, but if String is combination of numbers and operators, Why not just check if it ends with a digit?

You can use a regex something like "/^[0-9]" (Not tested though).