I have a string
我有一个字符串
String SQL = "SELECT POSITION('Bengal' IN STRING) from delivery";
I want to replace the POSITION() function from the SQL string with this String INSTR(STRING,'Bengal'). And in the POSITION function of SQL String 'Bengal' and STRING is not a fixed values it will change as per user requirement but POSITION,the open braces "(",IN and closing braces ")" is static. The final out put has to be look like this using Regular Expression.
我想用这个字符串INSTR(STRING,'Bengal')替换SQL字符串中的POSITION()函数。在SQL字符串'Bengal'的POSITION函数中,STRING不是固定值,它将根据用户要求而改变,但POSITION,开括号“(”,IN和右括号“)”是静态的。使用正则表达式,最终输出必须看起来像这样。
String SQL ="SELECT INSTR(STRING,'Bengal') from delivery";
So in the string if it repeats two times then it has to replace two time with corresponding arguments into the same string SQL. Any help will be appreciated.
所以在字符串中,如果它重复两次,那么它必须用相应的参数将两次替换为相同的字符串SQL。任何帮助将不胜感激。
1 个解决方案
#1
2
In Java, use this Regex:
在Java中,使用此正则表达式:
SQL = SQL.replaceAll("POSITION\\((.*?) IN ([A-Z]+)\\)", "INSTR($2, $1)");
Note, however, that it will work only for simple cases of the input String, if the first parameter is some expression and second is something more complex, it may not work. It will even work for multiple POSITION
expressions in the query, such as this:
但请注意,它仅适用于输入String的简单情况,如果第一个参数是某个表达式,第二个参数更复杂,则可能无效。它甚至可以用于查询中的多个POSITION表达式,例如:
String SQL = "SELECT POSITION('Bengal''s something IN d' IN STRING), POSITION('text' IN STRINGX) from delivery";
SQL = SQL.replaceAll("POSITION\\((.*?) IN ([A-Z]+)\\)", "INSTR($2, $1)");
// SQL now contains: "String SQL = "SELECT INSTR(STRING, 'Bengal''s something IN d'), INSTR(STRINGX, 'text') from delivery";"
If you want to completely correctly replace the function call, use proper sqlparser. In the past I used JSQLParser. It can handle even subselects as POSITION
parameters with nested POSITION
calls.
如果要完全正确地替换函数调用,请使用正确的sqlparser。过去我使用过JSQLParser。它甚至可以处理具有嵌套POSITION调用的POSITION参数的子选择。
#1
2
In Java, use this Regex:
在Java中,使用此正则表达式:
SQL = SQL.replaceAll("POSITION\\((.*?) IN ([A-Z]+)\\)", "INSTR($2, $1)");
Note, however, that it will work only for simple cases of the input String, if the first parameter is some expression and second is something more complex, it may not work. It will even work for multiple POSITION
expressions in the query, such as this:
但请注意,它仅适用于输入String的简单情况,如果第一个参数是某个表达式,第二个参数更复杂,则可能无效。它甚至可以用于查询中的多个POSITION表达式,例如:
String SQL = "SELECT POSITION('Bengal''s something IN d' IN STRING), POSITION('text' IN STRINGX) from delivery";
SQL = SQL.replaceAll("POSITION\\((.*?) IN ([A-Z]+)\\)", "INSTR($2, $1)");
// SQL now contains: "String SQL = "SELECT INSTR(STRING, 'Bengal''s something IN d'), INSTR(STRINGX, 'text') from delivery";"
If you want to completely correctly replace the function call, use proper sqlparser. In the past I used JSQLParser. It can handle even subselects as POSITION
parameters with nested POSITION
calls.
如果要完全正确地替换函数调用,请使用正确的sqlparser。过去我使用过JSQLParser。它甚至可以处理具有嵌套POSITION调用的POSITION参数的子选择。