我现在对java很新我尝试制作一个程序来检查DDL命令(不用sql连接只接受用户的文件并检查他们写命令DDL是对还是错)。
首先,我从用户那里读取文件
其次,我想找到字符串create table name ()
并获取字符串inside()来检查类似
create table name(a int,b int)
所以这是我的代码
Input file from user
Read file in string str
String Ck_create="create table \\D[^;]+\\([^;](.*?)+[^;]+\\)";
Pattern pattern = Pattern.compile(Ck_create);
Matcher matcher = pattern.matcher(str);
if (matcher.find())
{
matcher.group()
/*start to check line by line*/
}
else{/*error*/}
它工作正常但是当我创建多个表时(比如在sql中创建多个表时)程序只关心它遇到的第一个。它不能有像这样的文件中的很多字符串组
创建表名 ( name int, id int )
创建表格表名2 ( lastname int, 哇 )
程序只关心第一个表,但我也要检查表名2中的字符串。我该怎么办?
答案 0 :(得分:0)
像
这样的东西Matcher matcher = p.matcher("REGEXP");
while (matcher.find()) {
System.out.println(matcher.group());
}
答案 1 :(得分:0)
你必须在单行上进行迭代:
InputStream fis = null;
BufferedReader br = null;
String aFileLine;
String fileName = "the_file_name";
Pattern pattern = Pattern.compile("create table \\D[^;]+\\([^;](.*?)+[^;]+\\)");
Matcher mat = null;
try {
fis = new FileInputStream(fileName);
br = new BufferedReader(new InputStreamReader(fis));
// start to check line by line
while ((aFileLine = br.readLine()) != null) {
mat = pattern.matcher(aFileLine);
if (mat.find()) {
String s = mat.group(1);
// now you have your string in 's'
}
}
}
catch (FileNotFoundException e) {
System.err.println("File " + "'"+ fileName + "'" + "not found!!");
}
catch (IOException e) {
e.printStackTrace();
}
// Done with the file
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
br = null;
fis = null;
}