-2

I have a string something like this

Hello #'World'# , currently i am in #'world's'# best location.

I need to replace this all the chars between #' and '# using regex in java i need a final string should be in this format

Hello #'@@@@@'# , currently i am in #'@@@@@@@'# best location.
Naman Gala
  • 4,670
  • 1
  • 21
  • 55
  • 1
    possible duplicate of [Learning Regular Expressions](http://stackoverflow.com/questions/4736/learning-regular-expressions) – Andy Brown Sep 07 '15 at 07:34
  • 1
    @AndyBrown, well, the replacement depends on the (length of the) match, so it's not a simple call to `replaceAll`. – aioobe Sep 07 '15 at 07:38
  • Do you mean it must use `replaceAll()`, or is it ok to just use regex to find string to replace? Does it absolutely have to be regex? – Andreas Sep 07 '15 at 07:49

1 Answers1

1

Solution not using regex:

String input = "Hello #'World'# , currently i am in #'world's'# best location.";

StringBuilder buf = new StringBuilder(input.length());
int start = 0, idx1, idx2;
while ((idx1 = input.indexOf("#'", start)) != -1) {
    idx1 += 2;
    if ((idx2 = input.indexOf("'#", idx1)) == -1)
        break;
    buf.append(input, start, idx1); // append text up to and incl. "#'"
    for (; idx1 < idx2; idx1++)
        buf.append('@'); // append replacement characters
    start = idx2 + 2;
    buf.append(input, idx2, start); // append "'#"
}
buf.append(input, start, input.length()); // append text after last "'#"
String output = buf.toString();

System.out.println(input);
System.out.println(output);

Output

Hello #'World'# , currently i am in #'world's'# best location.
Hello #'@@@@@'# , currently i am in #'@@@@@@@'# best location.
Andreas
  • 154,647
  • 11
  • 152
  • 247