• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

replacing character at a beginning of a string with another at its end

 
Igor Mechnikov
Ranch Hand
Posts: 100
Chrome Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings and Salutations!

Please help to replace string "#xyz"with "xyz,".
Running

public class ReplaceChar {
public static void main(String[] args) {
String str = "#xyz";
String result = str.replaceAll("#(.*)", "\1,");
System.out.println(result);
}
}

outputs "," by itself.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look at the Javadocs for String.replaceAll, they refer you to Matcher.replaceAll...

...which refers you to Matcher.appendReplacement...

...which tell you that backslashes are not used to refer to a captured group. You need $1 instead.

[Note that if it was a backslash you needed, it would have to be \\1, because backslash has a special meaning in a string literal]
 
Igor Mechnikov
Ranch Hand
Posts: 100
Chrome Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much!
I really appreciate the references as well.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic