Win a copy of Transfer Learning for Natural Language Processing (MEAP) this week in the Artificial Intelligence and Machine Learning forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Paul Clapham
  • Devaka Cooray
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Liutauras Vilda
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Piet Souris
Bartenders:
  • salvin francis
  • Carey Brown
  • Frits Walraven

Regex question

 
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy,

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?
 
Ronald Schild
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aha.

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 ]
 
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
<blockquote>code:
<pre name="code" class="core">String s = "Some text \\\\r and some more \\\\r.";
System.out.println(s);
System.out.println(s.replace("\\\\r", "\\r"));
System.out.println(s.replaceAll("\\Q\\\\r\\E", "\\\\r"));
</pre>
</blockquote>
 
Hang a left on main. Then read this tiny ad:
Two software engineers solve most of the world's problems in one K&R sized book
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic