1

I have a String java like this :

String query= Select * from table where date between ('2016-05-03' and '2016-05-04' )

I wanted to delete brackets after between i tried :

 String search="between";
if(query.toLowerCase().indexOf(search.toLowerCase()) != -1){  
query=query.replaceAll("[()]","");
 }

It worked but If the query contains some brackets after or before the word 'between' they will be delete also.. Example :

SELECT column-names
 FROM table-name1
WHERE value IN (SELECT date 
               FROM table-name2 
              WHERE date between ('2016-05-03' and '2016-05-04' ))

I just want to delete two first brackets after the word 'between' to get this :

 SELECT column-names
 FROM table-name1
WHERE value IN (SELECT date 
               FROM table-name2 
              WHERE date between '2016-05-03' and '2016-05-04') 

Thanks for your help

John
  • 185
  • 1
  • 6
  • 21
  • Possible duplicate of [Java; String replace (using regular expressions)?](http://stackoverflow.com/questions/632204/java-string-replace-using-regular-expressions) – Julien Lopez Oct 17 '16 at 09:16

3 Answers3

1

You can represent in regex the whole structure you're trying to change :

between\s*\(([^)]*)\)

and transform it into

between $1

Where $1 is a reference to the [^)]* group which catches the content of the brackets.

The transformation will only occur if the between is followed by an open bracket and will remove the closest closing bracket.

See it in action !

Aaron
  • 24,009
  • 2
  • 33
  • 57
1

You need to remove the first ( after between and the last occurrence of ) after (. That means, you need to leverage greedy matching .* with DOTALL modifier so that the . could match linebreak symbols. Also, a [^(]* can help you grab anything that is not ( between between and the (:

String s = "SELECT column-names\n FROM table-name1\nWHERE value IN (SELECT date \n               FROM table-name2 \n              WHERE date between ('2016-05-03' and '2016-05-04' ))";
String search="(?s)(between[^(]*)\\((.*)\\)";
System.out.println(s.replaceFirst(search, "$1$2"));

See the Java demo

Details:

  • (?s) - the embedded DOTALL flag
  • (between[^(]*) - Group 1 capturing between and 0+ chars other than (
  • \\( - a ( is matched
  • (.*) - any 0+ chars as many as possible up to the last
  • \\) - literal ).

The $1 references to the Group 1 contents, and $2 to the Group 2 contents.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

I think below piece of code will solve your problem:

String query= "Select * from table where date between ('2016-05-03' and '2016-05-04')";
StringBuilder sbr = new StringBuilder(query);
sbr.deleteCharAt(sbr.indexOf("(", sbr.indexOf("between")));
sbr.deleteCharAt(sbr.indexOf(")", sbr.indexOf("between")));
query= sbr.toString();
krlzlx
  • 5,752
  • 14
  • 47
  • 55