jQuery in Action, 2nd edition*
The moose likes Java in General and the fly likes string replacement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "string replacement" Watch "string replacement" New topic
Author

string replacement

shankar vembu
Ranch Hand

Joined: May 10, 2001
Posts: 309
somehow got stuck with this.
I am trying to replace "_" with "\_" in my string. I tried String.replaceAll("_","\\_") but it wont work. I am not getting a backslash in my result string.
String.replace('_','\\') works but i cant use it becos I need the underbar also....
From regex pattern, it is clear that we can use \\ to escape a \, but i guess it is not being applied to the second arg. in String.replaceAll(regex,replacement) method.
WHat am i missing here
Shankar.
Shankar.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Originally posted by shankar vembu:
somehow got stuck with this.
I am trying to replace "_" with "\_" in my string. I tried String.replaceAll("_","\\_") but it wont work. I am not getting a backslash in my result string.
String.replace('_','\\') works but i cant use it becos I need the underbar also....
From regex pattern, it is clear that we can use \\ to escape a \, but i guess it is not being applied to the second arg. in String.replaceAll(regex,replacement) method.
WHat am i missing here
Shankar.
Shankar.


Can you post your code ? A string is immutable so you have to assign the String.replaceAll(..) to your result string.
shankar vembu
Ranch Hand

Joined: May 10, 2001
Posts: 309
Originally posted by Oliver Refle:


Can you post your code ? A string is immutable so you have to assign the String.replaceAll(..) to your result string.

ok , i dint mean to use my string directly.here is my code anyways,
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Java is turning your two slashes into one (the first is an escape for the second) and regex is turning \_ into _ because it thinks the slash is an escape for the following character. Try "\\\\_". Java turns that into \\_ and regex turns that into \_.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
shankar vembu
Ranch Hand

Joined: May 10, 2001
Posts: 309
Originally posted by Stan James:
Java is turning your two slashes into one (the first is an escape for the second) and regex is turning \_ into _ because it thinks the slash is an escape for the following character. Try "\\\\_". Java turns that into \\_ and regex turns that into \_.

oh yes, it works now. thank you james. i missed this point.
shankar
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: string replacement