This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes replacing character at a beginning of a string with another at its end Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "replacing character at a beginning of a string with another at its end" Watch "replacing character at a beginning of a string with another at its end" New topic
Author

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

Igor Mechnikov
Ranch Hand

Joined: Feb 13, 2011
Posts: 100

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.

String knock = "\u042F \u0418\u0433\u043e\u0440\u044c";
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4344
    
    8

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

Joined: Feb 13, 2011
Posts: 100

Thank you so much!
I really appreciate the references as well.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: replacing character at a beginning of a string with another at its end
 
Similar Threads
user defined data type
String replaceAll method removes backslashes in replacement string
Thread Question - Examlab Practice Exam 1
why String vlass reference variable holds content ?
Static Block