我有一个大sql文件的集合。从那些文件中我只想保留" CREATE TABLE"和"更改表格添加约束外键"声明。我可以用它来收集这两个正则表达式吗?我知道我可以使用grep,但我没有linux
答案 0 :(得分:2)
您可以构建一个小型Java程序来仅获取此类句子。 e.g:
String input = new String(Files.readAllBytes(Paths.get("file.sql")), "UTF-8");
String regex = "(?i)((create table|alter table add constraint foreign key)[^;]+;)"
.replace(" ", "\\s+");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
答案 1 :(得分:-1)
以下代码将返回您可以根据您的要求进行子串或其他操作的整行。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class Test extends BufferedReader {
String pattern;
public Test(Reader in, String pattern) {
super(in);
this.pattern = pattern;
}
public final String readLine() throws IOException {
String line;
do {
line = super.readLine();
} while ((line != null) && line.indexOf(pattern) == -1);
return line;
}
public static void main(String args[]) {
try {
Test in = new Test(new FileReader("test.txt"), "emement2");
String line;
while ((line = in.readLine()) != null)
System.out.println(line);
in.close();
} catch (Exception e) {
System.err.println(e);
}
}
}