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 Regex question 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 "Regex question" Watch "Regex question" New topic

Regex question

Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117

I'm trying to replace "\\r" into "\r". What I've come up with is someString.replaceAll("\\\\r", "\r"), but this replaces "\r" with "r", and "\\r" with "\r".

Can anyone explain to me why it is doing this?

Java hobbyist.
Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117

Every regex '\' must be doubled, but also every string '\'. It does not replace "\\r" with "\r", it replaces "\r" with "r", a bit of confusion on my side.

More '\' is the way to go.

edit, so: "\\\\\\\\r" matches "\\r" (as parsed result).
[ July 16, 2008: Message edited by: Ronald Schild ]
Piet Verdriet
Ranch Hand

Joined: Feb 25, 2006
Posts: 266
In your case, there is no real need to use regex (as far as I can see). A simple String.replace(...) will do the job as well, and that method does not take a regex as parameter.
But, if you do need regex, and you want to keep the escaping to a minimum, you can always use \\Q ... \\E to make the regex engine ignore any meta characters:
<pre name="code" class="core">String s = "Some text \\\\r and some more \\\\r.";
System.out.println(s.replace("\\\\r", "\\r"));
System.out.println(s.replaceAll("\\Q\\\\r\\E", "\\\\r"));
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Regex question
Similar Threads
What is the highest salar possible for a 5 yr exp Java /C++ developer in Chennai?
when and why we use FF and CR i,e.. \f and \r
Running two threads
Addition of 256bit unsigned integers