Replace multiple characters in a string in Java

后端 未结 4 424
暗喜
暗喜 2020-12-22 07:26

I have some strings with equations in the following format ((a+b)/(c+(d*e))).

I also have a text file that contains the names of each variable, e.g.:

4条回答
  •  遥遥无期
    2020-12-22 08:13

    Don't use String#replaceAll in this case if there is slight chance part you will replace your string contains substring that you will want to replace later, like "distance" contains a and if you will want to replace a later with "velocity" you will end up with "disvelocityance".

    It can be same problem as if you would like to replace A with B and B with A. For this kind of text manipulation you can use appendReplacement and appendTail from Matcher class. Here is example

    String input = "((a+b)/(c+(d*e)))";
    
    Map replacementsMap = new HashMap<>();
    replacementsMap.put("a", "velocity");
    replacementsMap.put("b", "distance");
    replacementsMap.put("c", "time");
    
    StringBuffer sb = new StringBuffer();
    Pattern p = Pattern.compile("\\b(a|b|c)\\b");
    Matcher m = p.matcher(input);
    while (m.find())
        m.appendReplacement(sb, replacementsMap.get(m.group()));
    m.appendTail(sb);
    
    System.out.println(sb);
    

    Output:

    ((velocity+distance)/(time+(d*e)))
    

    This code will try to find each occurrence of a or b or c which isn't part of some word (it doesn't have any character before or after it - done with help of \b which represents word boundaries). appendReplacement is method which will append to StringBuffer text from last match (or from beginning if it is first match) but will replace found match with new word (I get replacement from Map). appendTail will put to StringBuilder text after last match.


    Also to make this code more dynamic, regex should be generated automatically based on keys used in Map. You can use this code to do it

    StringBuilder regexBuilder = new StringBuilder("\\b(");
    for (String word:replacementsMap.keySet())
        regexBuilder.append(Pattern.quote(word)).append('|');
    regexBuilder.deleteCharAt(regexBuilder.length()-1);//lets remove last "|"
    regexBuilder.append(")\\b");
    String regex = regexBuilder.toString();
    

提交回复
热议问题