Problems with a regex


I have this equation 2x ^ 2 + 7x-1 which by means of a regex removes what are the following characters: [x], [x ^ n]. to be able to solve them by means of of the general formula.
This is my next code

public void resolver(String msg) throws IOException {
            System.out.println("No es una ecuación cuadrática");
        } else {
            //  System.out.println(msg);

        String[] lista = new String[3];
        Pattern p = Pattern.compile("^(?:([+-]?[0-9]+?|)x\^2)?(?:([+-]?\d+)x)?([+-]?\d+)?$");
        Matcher m = p.matcher(msg);
        while (m.find()){

            lista[0] =;
            lista[1] =;
            lista[2] =;
            lista[0] = "1";
        String a =  lista[0];
        String b =  lista[1];
        String c =  lista[2];

        Double a1 = Double.valueOf(a);
        Double b1 = Double.valueOf(b);
        Double c1 = Double.valueOf(c);

       System.out.println(a1+" "+b1+""+" "+c1);

     //  Double p1 = ((b1*b1)-(4*(a1*c1)));
       Double p2 = Math.sqrt((b1*b1)-(4*(a1*c1)));
       // System.out.println(p1);

       if(p2 <= 0){
           System.out.println("Raiz Imaginaria. No se puede Resolver");
       } else {

           x1 = (-b1  + p2) / (2*a1);
           x2 = (-b1  - p2) / (2*a1);
           System.out.println("X1 = " + " "+ x1);
           System.out.println("X2 = " + " "+ x2);
           String mensaje2 = "\n"+"X1 = "+x1+"\n"+"X2"+" "+x2;

The problem is that when someone puts a negative sign on the operation for example -x ^ 2 + 7x-1, the program takes it as if it were not a regular expression given to the validations.

Edit : Sorry, it does not appear as such an error, but in the regular expression does not recognize the equation if there is no number after the sign "-" and before "x ^ 2"

asked by Neto_Lozano 26.10.2018 в 21:29

1 answer


The problem is this piece: ([+-]?\d+|)

What do you mean:

  • An optional + or - sign
  • At least one number

-ó -

  • Nothing

That is to say, you could never have -x because the first possibility is the one allowed by the sign, but that number is mandatory.

It seems a problem to group the options. You probably wanted to write: ([+-]?(?:\d+|)) . In this way, you always allow the sign and then you have the two options (number or nothing)

Demo: ^(?:(\[+-\]?(?:\d+|))x\^\[0-9\])?(?:(\[+-\]?\d+)x)?(\[+-\]?\d+)?$

Although it still remains a strange way to write it. In these cases it is more common to use the quantifier * , which means 0 or more times, so ([+-]?\d*)

Demo: ^(?:(\[+-\]?\d*)x\^\[0-9\])?(?:(\[+-\]?\d+)x)?(\[+-\]?\d+)?$

answered by 02.11.2018 / 10:13