Replace multiple characters in a string in Java

后端 未结 4 411
暗喜
暗喜 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 07:50

    For string str, use the replaceAll() function:

    str = str.toUpperCase();  //Prevent substitutions of characters in the middle of a word
    str = str.replaceAll("A", "velocity");
    str = str.replaceAll("B", "distance");
    //etc.
    
    0 讨论(0)
  • 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<String, String> 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();
    
    0 讨论(0)
  • 2020-12-22 08:13

    I'd make a hashMap mapping the variable names to the descriptions, then iterate through all the characters in the string and replace each occurrance of a recognised key with it's mapping. I would use a StringBuilder to build up the new string.

    0 讨论(0)
  • 2020-12-22 08:14

    Using a hashmap and iterating over the string as A Boschman suggested is one good solution.

    Another solution would be to do what others have suggested and do a .replaceAll(); however, you would want to use a regular expression to specify that only the words matching the whole variable name and not a substring are replaced. A regex using word boundary '\b' matching will provide this solution.

    String variable = "a";
    String newVariable = "velocity";
    str.replaceAll("\\b" + variable + "\\b", newVariable);
    

    See http://docs.oracle.com/javase/tutorial/essential/regex/bounds.html

    0 讨论(0)
提交回复
热议问题