-1

I'm trying to replace a string occurrence in a query like this:

SELECT * FROM DB WHERE AGE = 3 and NAME = 'VALUE'

I'm using this regex: NAME\s*=\s*'[A-Z]+' that works fine here

This is how I've tried in Java:

query.replaceAll("NAME\s*=\s*'[A-Z]+'", replacementString); // Gives me Invalid escape sequence message
query.replaceAll("NAME\\s*=\\s*'[A-Z]+'", replacementString); 

Pattern pattern = Pattern.compile("NAME*= *'[A-Z]*'");
query.replaceAll(pattern.pattern(), replacementString);

Pattern pattern2 = Pattern.compile("NAME\\s*=\\s*'[A-Z]*'");                
query.replaceAll(pattern2.pattern(), replacementString);

None of this work.

How can I replace the NAME = 'VALUE' occurrence?

Wilder Pereira
  • 2,249
  • 3
  • 21
  • 31

2 Answers2

1

Java strings are immutable.

You need to assign the result of the replaceAll call back to the string:

query = query.replaceAll(...);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Try this,

query.replaceAll("NAME\\s*=\\s*'[A-Z]+'", replacementString); 
query.replaceAll("NAME\\s*=\\s*'[A-Z]+'", replacementString);

And then in your pattern,

Pattern pattern2 = Pattern.compile("NAME\\s*=\\s*'[A-Z]*'");                
query.replaceAll(pattern2.pattern(), replacementString);