Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - regex on sql query

I need to apply a java regex on sql query string to calculate the count of it. I have to get what is between the "first select" and "from" of the principal query. This is my example :

Query :
select name,(select age from subtable), adress from table where name in (select name from subtable1)

Result :
select count(*) from table where name in (select name from subtable1)

I was using replaceFirst("^(.*?)from", "select count(*) from") but it is not working because there is an sql query in the attribute.

Please anyone can help ?

like image 263
Youssef El Rhailani Avatar asked Dec 04 '25 04:12

Youssef El Rhailani


1 Answers

You can solve your problem using this regex ^(.*?)from(?![^(]*\\)):

str = str.replaceFirst("^(.*?)from(?![^(]*\\))", "select count(*) from");

Output

select count(*) from table where name in (select name from subtable1)

The idea is match from that is inside () parenthesis.


Demo

like image 80
YCF_L Avatar answered Dec 05 '25 19:12

YCF_L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!