"Si un ouvrier veut bien faire son travail, il doit d'abord affûter ses outils." - Confucius, "Les Entretiens de Confucius. Lu Linggong"
Page de garde > La programmation > How Can I Efficiently Replace Multiple Substrings in a Java String?

How Can I Efficiently Replace Multiple Substrings in a Java String?

Publié le 2025-03-24
Parcourir:622

How Can I Efficiently Replace Multiple Substrings in a Java String?

Replacing Multiple Substrings in a String Efficiently in Java

When confronted with the need to replace multiple substrings within a string, it is tempting to resort to the brute force approach of repeatedly applying the string.replace() method. However, this can be inefficient for large strings or when working with numerous strings.

Exploiting Regular Expressions

A more efficient solution involves leveraging regular expressions. Regular expressions allow you to define complex search patterns and perform text transformations in a single operation.

Example Usage

Consider a scenario where you want to replace tokens such as "%cat%" and "%beverage%" with values stored in a map. Using StringUtils from Apache Commons Lang, you can create a pattern and matcher as follows:

Map<String,String> tokens = new HashMap<>();
tokens.put("cat", "Garfield");
tokens.put("beverage", "coffee");

String template = "%cat% really needs some %beverage%.";

// Create pattern of the format "%(cat|beverage)%"
String patternString = "%(" + StringUtils.join(tokens.keySet(), "|") + ")%";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(template);

Next, you can use the matcher to find all occurrences of the tokens and replace them with the corresponding values:

StringBuffer sb = new StringBuffer();
while(matcher.find()) {
    matcher.appendReplacement(sb, tokens.get(matcher.group(1)));
}
matcher.appendTail(sb);

System.out.println(sb.toString());

Benefits of Regular Expressions

Once the regular expression is compiled, searching the input string is typically very fast. Additionally, regular expressions provide the flexibility to handle complex search patterns, such as those involving parentheses and quantifiers.

Dernier tutoriel Plus>

Clause de non-responsabilité: Toutes les ressources fournies proviennent en partie d'Internet. En cas de violation de vos droits d'auteur ou d'autres droits et intérêts, veuillez expliquer les raisons détaillées et fournir une preuve du droit d'auteur ou des droits et intérêts, puis l'envoyer à l'adresse e-mail : [email protected]. Nous nous en occuperons pour vous dans les plus brefs délais.

Copyright© 2022 湘ICP备2022001581号-3