How to recursively replace the string with regex in Java

advertisements

I am looking for some way to replace string by regex in Java for case as below:

(BatteryTemperature > 12.23)

What I need to do is replace the 12.23 to 54.01, actually is Celsius to Fahrenheit degree as below:

(BatteryTemperature > 54.01)

However, the string may be different condition like:

(Signal = 90) AND (BatteryTemperature > 12.23)

or

(Signal = 90) OR (Latitude = 123.653) AND (BatteryTemperature > 12.23)

I have regex as below

(\\((\\w+) (>|<|=) (\\d+.\\d+)\\))

However, the regex (?R) seems not support in java?

Did there any other way to replace the BatteryTemperature value by converted one.

(Signal = 90) OR (Latitude = 123.653) AND (BatteryTemperature > 54.01)

Any help is appreciated.


I have solved my question by replaceAll() and Pattern, but not quite sure if there has another way better then this.

        String sample = "(Signal = 90) OR (Latitude = 123.653) AND (BatteryTemperature > 54.01)"
        String key = "BatteryTemperature";
        String[] array = sample.split(" AND | OR ");
        for(String tmp :array)
        {
            System.out.println("String: " + tmp);
            Pattern pattern = Pattern.compile("\\(("+key+") (>|<|=) (-?\\d+.\\d*)\\)");
            Matcher matcher = pattern.matcher(tmp);
            if(matcher.find())
            {
                for(int i = 0; i<=matcher.groupCount(); i++)
                {
                    if(matcher.group(i).equals(key))
                    {
                        sample = sample.replaceAll(matcher.group(i-1), key + " " + matcher.group(i+1) + " " + convertCelsiusToFahrenheit(matcher.group(i+2)));
                    }
                }
            }
        }