Reputation: 575
I have an SQL string defined as follows:
String query = "SELECT NAME,, AGE,, Dep, as, Department, FROM, Employee, WHERE =, :param1";
I want to make the query as: SELECT NAME, AGE, Dep as Department FROM Employee WHERE = :param1
Can someone please help with this in Java?
I have tried the query.repaceAll(",,", "");
but it does not seem to work properly.
Upvotes: 0
Views: 405
Reputation: 4258
Try this:
String newQuery = Stream.of(query.split(",,"))
.map(s -> s.replace(",", ""))
.collect(Collectors.joining(","));
Upvotes: 0
Reputation: 14999
It looks like the query was generated from a list that was then joined by ", ". Therefore, all you need to do is
query = query.replaceAll(", ", "");
I will mention again as others have already done that this is a terrible idea with all kinds of security issues.
Upvotes: 1
Reputation: 1936
First of all, you should try to fix the source of that query.
Here is an easy trick avoiding the use of regex:
String query = "SELECT NAME,, AGE,, Dep, as, Department, FROM, Employee, WHERE =, :param1";
query = query.replace(",,", "#").replace(",", "").replace("#", ",");
System.out.println(query);
SELECT NAME, AGE, Dep as Department FROM Employee WHERE = :param1
Upvotes: 1
Reputation: 5930
It might be better to fix the code that adds those additional commas.
Anyway, query.replaceAll(",+", ",")
will squash any sequence of commas into one. Then you are stuck with the commas around the as
keywords. Those you can replace by .replaceAll(",\\s*[Aa][Ss]\\s*,", " as ")
. Similarly for the other keywords like WHERE
, FROM
, ...
Upvotes: 1