-4

I am new to regular expressions. I am testing an iterative regular expression. For the first time it works but second time pattern isn't initializing again.

Here is my code:

    public static void main(String  a[])
    {
        String s="1+2+4*5*tan(tan(30))-5.8+tan(30)";
        Pattern p;
        Matcher m;  
        while(s.contains("tan("))
        {
            double[] x=new double [5];  
            p=Pattern.compile("tan\\([0-9]+\\)");
            m=p.matcher(s);
            int i=0;

            while(m.find())
            {

                System.out.println(m.group());
                x[i]=Math.tan(Math.toRadians(Double.parseDouble(m.group().replace("tan(","").replace(")",""))));
                i++;
            }


            for(int z=0;z<i;z++)
            {
                s=s.replaceFirst("tan\\([0-9]+\\)",""+x[z]);


            }
         }
         System.out.println(s);

    }
sfjac
  • 7,119
  • 5
  • 45
  • 69
Abhishek
  • 3
  • 2
  • 1
    What do you mean by "*...pattern isn't initializing again*"? What behaviour you ware expecting and what did you observe instead? – Pshemo Sep 05 '17 at 19:25
  • when the loop runs for second time p=Pattern.compile("tan\\([0-9]+\\)"); is not working – Abhishek Sep 05 '17 at 19:27
  • Which loop? There are 3. What's the definition of "not working"? – Abhijit Sarkar Sep 05 '17 at 19:28
  • 1
    Please explain ["is not working"](http://importblogkit.com/2015/07/does-not-work/). – Pshemo Sep 05 '17 at 19:28
  • 1
    Why use regex for this? [Evaluating a math expression given in string form](https://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form) – ctwheels Sep 05 '17 at 19:28
  • I mean loop is working but pattern is not matching again . while(s.contains("tan(")) this loop . – Abhishek Sep 05 '17 at 19:32
  • If u run the code I think it will be clear – Abhishek Sep 05 '17 at 19:32
  • 1
    Wait, are you trying to calculate the `tan(x)` result and paste it back into the `s` string? You only need one loop here. However, then you **must** have a look at [Evaluating a math expression given in string form](https://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form) – Wiktor Stribiżew Sep 05 '17 at 19:39

1 Answers1

0

Check your regex.

"tan\\([0-9]+\\)"

This will not accept decimal numbers. Hence the first two tan(30) gets resolved, but then the tan(decimal numbers) is not passing the regex and it keeps going on in a loop.

Soumya
  • 1,350
  • 3
  • 19
  • 34