This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Problems with replaceAll() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problems with replaceAll()" Watch "Problems with replaceAll()" New topic

Problems with replaceAll()

S. Lohi

Joined: May 21, 2004
Posts: 11
I am trying to convert a match-string to a format that my java program could understand.

Lets say the string is str = "foo*bar*".
I try to convert it to java format using str.replaceAll("*", ".*").
Shouldn't be a big deal, I figure, but unfortunately when the program tries to execute that line of code hell breaks loose. I get a dozen Errors and Exceptions, starting with

java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0

I know that happens when the string is like "*foo*bar" (starting with "*"), but why does it happen in this case?

Any help would be appreciated.

Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
"*" is a special character apparently. You might need to escape it with the traditional "\".

S. Lohi

Joined: May 21, 2004
Posts: 11
Tried that, gives an "invalid escape sequence".
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
use double \ like "\\*"
S. Lohi

Joined: May 21, 2004
Posts: 11
Well, that was... simple ( ).

Thank you very much.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
When figuring out regular expression patterns, as quick references I like to have available the Pattern class documentation, and the two introductory articles I wrote on the java.util.regex package, which can be found listed at (search for regex).

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Problems with replaceAll()
It's not a secret anymore!