File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes How to replace character *, using .replaceAll Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to replace character *, using .replaceAll" Watch "How to replace character *, using .replaceAll" New topic

How to replace character *, using .replaceAll

eileen keeney
Ranch Hand

Joined: May 04, 2009
Posts: 51
ok, I am trying to replace the character "*", with " [A-Za-z0-9]*"

String oldStr = "XYZ*";
String newStr = oldStr.replaceAll("\*", "[A-Za-z0-9]*");
System.out.println("newStr=" + newStr + "\n");

This one gives me illegal escape character

String oldStr = "XYZ*";
String newStr = oldStr.replaceAll("*", "[A-Za-z0-9]*");
System.out.println("newStr=" + newStr + "\n");

This one compiles, but then gives me a dangling meta character error when I run it.

Trying to replace another character, such as Y, works fine doing this:
String oldStr = "XYZ*";
String newStr = oldStr.replaceAll("Y", "[A-Za-z0-9]*");
System.out.println("newStr=" + newStr + "\n");

That compiles and runs and works. So my basic syntax (for replacing non meta characters) is correct here.

So how do I take a string, and replace every occurrence of * with A-Za-z0-9]*
If I do not escape it, it is read as a meta character.
If I do escape it, it tells me it is an illegal use of an escape character.


eileen keeney
Ranch Hand

Joined: May 04, 2009
Posts: 51
I found the answer in another forum,
So in case anyone else stumbles on this doing a search, the answer is to use double escape characters.

This works:
String oldStr = "XYZ*";
String newStr = oldStr.replaceAll("\\*", "[A-Za-z0-9]*");
System.out.println("newStr=" + newStr + "\n");

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 37903
Welcome to JavaRanch

You need to use \\ instead of \.

The reason is that the String literal turns the \\ into a single \ before it analyses the regular expression so you get a proper \*. You will occasionally have to use \\\\ in regular expressions, or even \\\\\\\\
jQuery in Action, 2nd edition
subject: How to replace character *, using .replaceAll
Similar Threads
doubt about string replacement
regular expression
Replace text by HTML links
Text Area Formatting