package com.demo;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DDLParse3 {
public static void main(String[] args) {
String filePath = "D:\\XuDeZhi\\Desktop\\test2.txt";
String regex = "(?i)table\\s+\"([^\".]+)\"\\.";
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
boolean inCreateTableStatement = false;
StringBuilder statementBuilder = new StringBuilder();
Stack<Character> bracketStack = new Stack<>();
Map<String, StringBuilder> tableStatements = new HashMap<>();
String currentTableName = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.toLowerCase().contains("table") && line.contains(".")) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
currentTableName = matcher.group(1);
}
line = line.replaceAll(regex, "TABLE ");
}
if (inCreateTableStatement) {
statementBuilder.append(line).append("\n");
for (char c : line.toCharArray()) {
if (c == '(') {
bracketStack.push(c);
} else if (c == ')') {
bracketStack.pop();
if (bracketStack.isEmpty()) {
inCreateTableStatement = false;
String createTableStatement = statementBuilder.toString().trim();
processCreateTableStatement(createTableStatement, currentTableName, tableStatements);
statementBuilder.setLength(0);
break;
}
}
}
} else if (line.startsWith("CREATE TABLE")) {
inCreateTableStatement = true;
statementBuilder.append(line).append("\n");
for (char c : line.toCharArray()) {
if (c == '(') {
bracketStack.push(c);
}
}
} else if (currentTableName != null) {
appendToPreviousTable(line, currentTableName, tableStatements);
}
}
// 输出每个表的相关语句
for (Map.Entry<String, StringBuilder> entry : tableStatements.entrySet()) {
String tableName = entry.getKey();
StringBuilder tableStatement = entry.getValue();
System.out.println("Table: " + tableName);
System.out.println(tableStatement.toString());
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void processCreateTableStatement(String statement, String tableName, Map<String, StringBuilder> tableStatements) {
// 将表的创建语句添加到对应的 StringBuilder 中
tableStatements.computeIfAbsent(tableName, k -> new StringBuilder()).append(statement).append("\n");
}
private static void appendToPreviousTable(String line, String tableName, Map<String, StringBuilder> tableStatements) {
// 将当前行添加到指定表的相关语句中
StringBuilder tableStatement = tableStatements.get(tableName);
tableStatement.append(line).append("\n");
}
}
自测代码
最新推荐文章于 2024-04-23 18:27:30 发布