Replace All Occurrences of a String Using Stringbuilder

Replacing mutiple occurrences of string using string builder by regex pattern matching

A regex solution like this is too fragile. If you need to parse any arbitrary SQL, you need a dedicated parser. There are examples on how to parse SQL properly in Parsing SQL code in C#.

If you are sure there are no "wild", unbalaned ( and ) in your input, you may use a regex as a workaround, for a one-off job:

var result = Regex.Replace(s, @"('[^']+')\s*=\s*(\w+\((?>[^()]+|(?<o>\()|(?<-o>\)))*\))", "\n $2 as $1");

See the regex demo.

Details

  • ('[^']+') - Capturing group 1 ($1): ', 1 or more chars other than ' and then '
  • \s*=\s* - = enclosed with 0+ whitespaces
  • (\w+\((?>[^()]+|(?<o>\()|(?<-o>\)))*\)) - Capturing group 2 ($2):

    • \w+ - 1+ word chars
    • \((?>[^()]+|(?<o>\()|(?<-o>\)))*\) - a (...) substring with any amount of balanced (...)s inside (see my explanation of this pattern).

Replacing All Chars (In StringBuilder) at their Index from of their occurrence another string

Try this:

    String guess = "l";
int start = 0;
do {
int index = theWord.indexOf(guess, start);
if(index >= 0) {
wordTemplate.replace(index, index + 1, guess);
start = index + 1;
} else
break;
} while (true);

System.out.println(wordTemplate);

StringBuilder vs. String considering replace

It is true that StringBuilder tends to be better than concatenating or modifying Strings manually, since StringBuilder is mutable, while String is immutable and you need to create a new String for each modification.

Just to note, though, the Java compiler will automatically convert an example like this:

String result = someString + someOtherString + anotherString;

into something like:

String result = new StringBuilder().append(someString).append(someOtherString).append(anotherString).toString();

That said, unless you're replacing a whole lot of Strings, go for whichever is more readable and more maintainable. So if you can keep it cleaner by having a sequence of 'replace' calls, go ahead and do that over the StringBuilder method. The difference will be negligible compared to the stress you save from dealing with the sad tragedy of micro-optimizations.

PS

For your code sample (which, as OscarRyz pointed out, won't work if you have more than one "$VARIABLE1" in someString, in which case you'll need to use a loop), you could cache the result of the indexOf call in:

someString.replace(someString.indexOf("$VARIABLE1"), someString.indexOf("$VARIABLE1")+10, "abc");

With

int index = someString.indexOf("$VARIABLE1");    
someString.replace(index, index+10, "abc");

No need to search the String twice :-)

how to replace all occurrences of a string inside tags using regex in java

We can try using a formal regex pattern matcher here. Match on the pattern <abc~a>(.*?)<abc~a>, and for each match append the tag with src replaced by abc. Here is a sample code:

String input = "Here is a src <abc~a>I am an src customer<abc~b> also another src here.";
Pattern p = Pattern.compile("<abc~a>(.*?)<abc~b>");
Matcher m = p.matcher(input);
StringBuffer buffer = new StringBuffer();

while(m.find()) {
String replace = "<abc~a>" + m.group(1).replaceAll("\\bsrc\\b", "abc") + "<abc~b>";
m.appendReplacement(buffer, replace);
}
m.appendTail(buffer);

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

This prints:

Here is a src <abc~a>I am an abc customer<abc~b> also another src here.

Note that in many other languages we could have used a regex callback function. But core Java does not support this functionality, so we have to iterate over the entire input.

Replace character in StringBuilder

If don't want to convert the StringBuilder to a String or you need to keep using it/preserve it, then you could do something like this...

for (int index = 0; index < sb.length(); index++) {
if (sb.charAt(index) == '-') {
sb.setCharAt(index, '/');
}
}

If you don't care then you could do something like...

String value = sb.toString().replace("-", "/");

String builder replace elements at even indexes in string

Some things I will correct, but @Nikolai Dmitriev already pointed some of them out.

  1. The n is needed, even though @Nikolai Dmitriev said it's not. Since you want to replace it with its ASCII value. However, you can shorten it to String a = String.valueOf((int) c); or even get rid of the c and just straight up use `String a = String.valueOf((int) sb.charAt(i));
  2. You are using sb.replace(char start, char end, String str); while the function should accept sb.replace(int start, int end, String str);. To correct this, just use sb.replace(i, i + 1, a);. Notice that you use end = i + 1 because the StringBuilder replace function end value is exclusive (not including).
  3. Initialize result at the end. The variable has a scope of inside the for loop if you do it inside, and since you want to return it, you would want to initialized it after you finish replacing all even-indices.


Related Topics



Leave a reply



Submit