File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string replacement

 
shankar vembu
Ranch Hand
Posts: 309
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 309
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 \_.
 
shankar vembu
Ranch Hand
Posts: 309
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic