生成一段java代码,通过正则get table name by one mysql insert sql
时间: 2024-05-01 12:17:32 浏览: 10
可以通过以下代码获取一个 MySQL 插入语句中的表名:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
private static final String INSERT_SQL = "INSERT INTO table_name (col1, col2, col3) VALUES (val1, val2, val3)";
public static void main(String[] args) {
String regex = "^INSERT INTO ([^\\s]+) \\(";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(INSERT_SQL);
if (matcher.find()) {
String tableName = matcher.group(1);
System.out.println("Table Name: " + tableName);
} else {
System.out.println("Table Name not found!");
}
}
}
```
其中,正则表达式 `^INSERT INTO ([^\s]+) \(` 匹配 `INSERT INTO` 后面的表名,`^` 表示匹配行首,`[^\s]+` 匹配不包含空格的任意字符(即表示表名),`\(` 表示匹配左括号。匹配成功后,使用 `group(1)` 方法获取正则表达式中第一个括号内的内容,即表名。
运行上述代码,可以得到以下输出:
```
Table Name: table_name
```