• Post Reply Bookmark Topic Watch Topic
  • New Topic

String.replaceAll function error  RSS feed

 
Yugan Singams
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hi All,

I am unable to replace a string with $$$ in my String .


String s="select * from table where lastDate between ### and $$$ "

s=s.replaceAll("###", "'"+ fromDate +"'"); here ### is replaced by fromDate
s=s.replaceAll("$$$", "'"+ toDate +"'"); but $$$ is not replace with toDate but its showing as $$$ 'DD/MM/YYYY'


why this is happening
 
Richard Tookey
Bartender
Posts: 1166
17
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first argument to replaceAll() is a regular expression and in a regular expression the $ characters is a Meta characters and means the end of line. To replace a $ you must escape it in the regular expression so that it no longer has it's special meaning and the simplest way is to prefix it by \\ . Note - the \\ is needed rather than just \ because Java uses \ as a Meta character ! Messy but ... .
 
Campbell Ritchie
Marshal
Posts: 56595
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch
Are you trying to pick up the dollar sign with a regular expression? But in regular expressions the dollar sign means the end of the line. You can find out all about it in the Java Tutorials. You might have to escape the dollar signs like this \\$
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Richard Tookey wrote:To replace a $ you must escape it in the regular expression so that it no longer has it's special meaning and the simplest way is to prefix it by \\ ...

@Yugan: Or use s = s.replace("$$$", "'"+ toDate +"'") instead.

The only drawback with that method is that you can only use it to replace all occurrences.

Winston
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yugan Singams, welcome to the Ranch.

It looks like you want to use this to replace parameters in an SQL statement. Instead of manually trying to build an SQL statement like this, you should use PreparedStatement instead. This is more efficient (the database can cache the statement, so that it doesn't need to interpret it every time you execute it) and safer (because the JDBC driver will escape special characters, which prevents SQL injection attacks).

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!