• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to replace character *, using .replaceAll

 
Ranch Hand
Posts: 56
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.

Thanks





 
eileen keeney
Ranch Hand
Posts: 56
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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");

 
Marshal
Posts: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 \\\\\\\\
reply
    Bookmark Topic Watch Topic
  • New Topic