Java - regex on sql query
I need to apply java regex string in sql query to calculate count . I have to get what is between " first select " and " from " the main query. This is my example:
Request: 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 have used replaceFirst("^(.*?)from", "select count(*) from")
but it doesn't work because there is a sql query in the attribute.
Please can anyone help?
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 the coincidence from
that is inside ()
.
Demo