简体   繁体   English

用Java替换字符串中的多个字符

[英]Replace multiple characters in a string in Java

I have some strings with equations in the following format ((a+b)/(c+(d*e))) .我有一些带有以下格式的方程的字符串((a+b)/(c+(d*e)))

I also have a text file that contains the names of each variable, eg:我还有一个包含每个变量名称的文本文件,例如:

a velocity
b distance
c time

etc...等等...

What would be the best way for me to write code so that it plugs in velocity everywhere a occurs, and distance for b , and so on?我编写代码的最佳方式是什么,以便在a出现的任何地方插入velocity ,以及b distance ,等等?

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" .不要使用String#replaceAll在这种情况下,如果有轻微的机会部分,你将取代你的字符串包含的子字符串,你将要在以后更换,像"distance"中含有a ,如果你想更换a后来与"velocity"你最终会得到"disvelocityance"

It can be same problem as if you would like to replace A with B and B with A .它可以是同样的问题,如果你想更换ABBA For this kind of text manipulation you can use appendReplacement and appendTail from Matcher class.对于这种文本操作,您可以使用Matcher类中的appendReplacementappendTail 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 ).此代码将尝试查找不属于某个单词的abc每次出现(它之前或之后没有任何字符 - 在表示单词边界\\b帮助下完成)。 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). appendReplacement是一种方法,它将从最后一个匹配项(或从头开始,如果它是第一个匹配项)附加到 StringBuffer 文本,但会将找到的匹配项替换为新单词(我从 Map 中获取替换)。 appendTail will put to StringBuilder text after last match. appendTail将在最后一次匹配后放入 StringBuilder 文本。


Also to make this code more dynamic, regex should be generated automatically based on keys used in Map.同样为了使此代码更具动态性,应根据 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();

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.我会制作一个 hashMap 将变量名称映射到描述,然后遍历字符串中的所有字符,并用它的映射替换每个已识别键的出现。 I would use a StringBuilder to build up the new string.我会使用 StringBuilder 来构建新字符串。

Using a hashmap and iterating over the string as A Boschman suggested is one good solution.使用哈希图并按照 A Boschman 的建议迭代字符串是一个很好的解决方案。

Another solution would be to do what others have suggested and do a .replaceAll();另一种解决方案是按照其他人的建议进行操作并执行 .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.使用字边界 '\\b' 匹配的正则表达式将提供此解决方案。

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

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

For string str , use the replaceAll() function:对于字符串str ,使用replaceAll()函数:

str = str.toUpperCase();  //Prevent substitutions of characters in the middle of a word
str = str.replaceAll("A", "velocity");
str = str.replaceAll("B", "distance");
//etc.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM