Remplacez toutes les occurrences d’une chaîne par SsortingngBuilder?

Est-ce que quelque chose me manque ou est-ce que SsortingngBuilder manque de la même fonction “remplacer toutes les occurrences d’une chaîne A par une chaîne B” que la classe Ssortingng normale? La fonction de remplacement de SsortingngBuilder n’est pas la même. Est-il possible d’y parvenir de manière plus efficace sans générer plusieurs chaînes à l’aide de la classe Ssortingng normale?

Eh bien, vous pouvez écrire une boucle:

 public static void replaceAll(SsortingngBuilder builder, Ssortingng from, Ssortingng to) { int index = builder.indexOf(from); while (index != -1) { builder.replace(index, index + from.length(), to); index += to.length(); // Move to the end of the replacement index = builder.indexOf(from, index); } } 

Notez que dans certains cas, il peut être plus rapide d’utiliser lastIndexOf , travaillant à l’arrière. Je soupçonne que c’est le cas si vous remplacez une chaîne longue par une chaîne courte. Ainsi, lorsque vous arrivez au début, les remplacements ont moins à copier. De toute façon, cela devrait vous donner un sharepoint départ.

Vous pouvez utiliser Pattern / Matcher . De la javadocs Matcher:

  Pattern p = Pattern.comstack("cat"); Matcher m = p.matcher("one cat two cats in the yard"); SsortingngBuffer sb = new SsortingngBuffer(); while (m.find()) { m.appendReplacement(sb, "dog"); } m.appendTail(sb); System.out.println(sb.toSsortingng()); 

Regardez JavaDoc de la méthode replaceAll de la classe Ssortingng :

Remplace chaque sous-chaîne de cette chaîne qui correspond à l’expression régulière donnée avec le remplacement donné. Une invocation de cette méthode de la forme str.replaceAll (regex, repl) donne exactement le même résultat que l’expression

java.util.regex.Pattern.comstack (regex) .matcher (str) .replaceAll (repl)

Comme vous pouvez le voir, vous pouvez utiliser Pattern et Matcher pour le faire.

La classe org.apache.commons.lang3.text.StrBuilder dans Apache Commons Lang permet les remplacements:

 public StrBuilder replaceAll(Ssortingng searchStr, Ssortingng replaceStr) 

* Cela ne reçoit pas une expression régulière mais une simple chaîne.

@Adam: Je pense que dans votre extrait de code, vous devez suivre la position de départ de m.find () car le remplacement de chaîne peut modifier le décalage après le dernier caractère correspondant.

 public static void replaceAll(SsortingngBuilder sb, Pattern pattern, Ssortingng replacement) { Matcher m = pattern.matcher(sb); int start = 0; while (m.find(start)) { sb.replace(m.start(), m.end(), replacement); start = m.start() + replacement.length(); } } 

Même la plus simple utilise la fonction Ssortingng ReplaceAll elle-même. Vous pouvez l’écrire comme

 SsortingngBuilder sb = new SsortingngBuilder("Hi there, are you there?") System.out.println(Pattern.comstack("there").matcher(sb).replaceAll("niru")); 

java.util.regex.Pattern.matcher (CharSequence s) peut utiliser un SsortingngBuilder comme argument pour que vous puissiez trouver et remplacer chaque occurrence de votre modèle à l’aide de start () et end () sans appeler builder.toSsortingng ()

Utilisez le suivant:

 /** * Utility method to replace the ssortingng from SsortingngBuilder. * @param sb the SsortingngBuilder object. * @param toReplace the Ssortingng that should be replaced. * @param replacement the Ssortingng that has to be replaced by. * */ public static void replaceSsortingng(SsortingngBuilder sb, Ssortingng toReplace, Ssortingng replacement) { int index = -1; while ((index = sb.lastIndexOf(toReplace)) != -1) { sb.replace(index, index + toReplace.length(), replacement); } } 

Voici un remplacement sur place qui modifiera le passé dans SsortingngBuilder. J’ai pensé que je posterais ceci car je cherchais à faire remplacer tout sans créer une nouvelle chaîne.

 public static void replaceAll(SsortingngBuilder sb, Pattern pattern, Ssortingng replacement) { Matcher m = pattern.matcher(sb); while(m.find()) { sb.replace(m.start(), m.end(), replacement); } } 

J’ai été choqué de la simplicité du code (pour une raison quelconque, je pensais que changer le SsortingngBuilder en utilisant le matcher allait déclencher le début / la fin du groupe mais ce n’est pas le cas).

C’est probablement plus rapide que les autres réponses de regex parce que le modèle est déjà compilé et que vous ne créez pas de nouvelle chaîne, mais je n’ai fait aucune parsing comparative.

Que diriez-vous de créer une méthode et laisser Ssortingng.replaceAll faire pour vous:

 public static void replaceAll(SsortingngBuilder sb, Ssortingng regex, Ssortingng replacement) { Ssortingng aux = sb.toSsortingng(); aux = aux.replaceAll(regex, replacement); sb.setLength(0); sb.append(aux); } 
 public static Ssortingng replaceCharsNew(Ssortingng replaceStr,Map replaceStrMap){ SsortingngBuilder replaceStrBuilder = new SsortingngBuilder(replaceStr); Set keys=replaceStrMap.keySet(); for(Ssortingng invalidChar:keys){ int index = -1; while((index=replaceStrBuilder.indexOf(invalidChar,index)) !=-1){ replaceStrBuilder.replace(index,index+invalidChar.length(),replaceStrMap.get(invalidChar)); } } return replaceStrBuilder.toSsortingng(); } 

J’ai trouvé cette méthode: Matcher.replaceAll (remplacement de chaîne); Dans java.util.regex.Matcher.java vous pouvez voir plus:

  /** * Replaces every subsequence of the input sequence that matches the * pattern with the given replacement ssortingng. * * 

This method first resets this matcher. It then scans the input * sequence looking for matches of the pattern. Characters that are not * part of any match are appended directly to the result ssortingng; each match * is replaced in the result by the replacement ssortingng. The replacement * ssortingng may contain references to captured subsequences as in the {@link * #appendReplacement appendReplacement} method. * *

Note that backslashes (\) and dollar signs ($) in * the replacement ssortingng may cause the results to be different than if it * were being treated as a literal replacement ssortingng. Dollar signs may be * treated as references to captured subsequences as described above, and * backslashes are used to escape literal characters in the replacement * ssortingng. * *

Given the regular expression a*b, the input * "aabfooaabfooabfoob", and the replacement ssortingng * "-", an invocation of this method on a matcher for that * expression would yield the ssortingng "-foo-foo-foo-". * *

Invoking this method changes this matcher's state. If the matcher * is to be used in further matching operations then it should first be * reset.

* * @param replacement * The replacement ssortingng * * @return The ssortingng constructed by replacing each matching subsequence * by the replacement ssortingng, substituting captured subsequences * as needed */ public Ssortingng replaceAll(Ssortingng replacement) { reset(); SsortingngBuffer buffer = new SsortingngBuffer(input.length()); while (find()) { appendReplacement(buffer, replacement); } return appendTail(buffer).toSsortingng(); }

Oui. Il est très simple d’utiliser la méthode Ssortingng.replaceAll() :

 package com.test; public class Replace { public static void main(Ssortingng[] args) { Ssortingng input = "Hello World"; input = input.replaceAll("o", "0"); System.out.println(input); } } 

Sortie:

 Hell0 W0rld