将sql语句中的表名加表前缀
问题描述
将 insert into table (item1, item2, itsm3) values (value1, value2, value3) 语句中的表名加前缀,但是insert 与into,into 与table之间的空格数量不确定到底有多少
实现方案
利用正则表达式进行替换
创建字符串转换工具类
package com.wy.mycode.algorithm.string;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author HelloWorld
* @create 2022/6/25 08:50
* @email helloworld.dng@gmail.com
*/
public class SwitchStringUtil {
/**
* @description 按指定规则替换字符传
* @author HelloWorld
* @create 2022/6/25 08:55
* @param str 待转换的字符串
* @param rule 转换规则
* @param target 转换子串
* @return java.lang.String
*/
public String switchStringByRule(String str, String rule, String target) {
Pattern pattern = Pattern.compile(rule);
Matcher matcher = pattern.matcher(str);
return matcher.replaceFirst(target);
}
}
实现按规则增加表名前缀的方法
package com.wy.mycode.algorithm.string;
/**
* @author HelloWorld
* @create 2022/6/25 10:09
* @email helloworld.dng@gmail.com
*/
public class AlterTableName {
/** 匹配sql语句中的 insert into 规则*/
private static final String SWITCH_RULE = "insert \\s*into \\s*";
/**
* @description
* @author HelloWorld
* @create 2022/6/25 10:24
* @param sql 需要转换的sql
* @param prefix 表名前缀
* @return java.lang.String
*/
private String doAlterTableName(String sql, String prefix) {
SwitchStringUtil switchStringUtil = new SwitchStringUtil();
String target = "insert into " + prefix;
return switchStringUtil.switchStringByRule(sql, SWITCH_RULE, target);
}
public static void main(String[] args) {
String str = "insert into table (item1, item2) values (value1, value2)";
AlterTableName alterTableName = new AlterTableName();
System.out.println(alterTableName.doAlterTableName(str, "PD_"));
}
}