Search code examples
javaregexreplaceall

String replaceAll with specific numeric values with a double


I have a requirement to replace a given string expression with numbers.

E.g: A string 1+3+5 needs to replaced with following values

1 = 270.5
3 = 377.5
5 = 377.5

But it not working as expected.

Actual Result

270.5+377.377.5+377.5

Expected Result

270.5+377.5+377.5

Note: I used word boundary \b

Thanks in advance.


Solution

  • I suggest using a hash map to define the replacements, and replace using Matcher#appendReplacement with a very simple \d+ regex (since your input contains int values only):

    import java.util.*;
    import java.util.regex.*;
    import java.lang.*;
    import java.io.*;
    
    public class HelloWorld{
    
         public static void main(String []args){
            String s = "1+3+5";
            Map<String, String> map = new HashMap<String, String>();
            map.put("1", "270.5");
            map.put("3", "377.5");
            map.put("5", "377.5");
            StringBuffer result = new StringBuffer();
            Matcher m = Pattern.compile("\\d+").matcher(s);
            while (m.find()) {
                String value = map.get(m.group());
                if (value != null) {
                    m.appendReplacement(result, value);
                } else {
                    m.appendReplacement(result, m.group());
                }
            }
            m.appendTail(result);
            System.out.println(result.toString());
         }
    }