java - 用于读取 'create table' sql 语句的正则表达式

标签 java regex

我目前正在使用从文件中读取的行手动编写此代码,并尝试读取表开始处的所有表 ddl a_

这个的输入:

Other stuff: 

Other stuff: 
create table a_table1 (
    id number(10,0) not null,
    timestamp number(19,0) not null,
    primary key (id)
)
stuff
create table a_table2 (
    id number(10,0) not null,
    primary key (id)
)

Other stuff: 
create table b_table1 (
    id number(10,0) not null,
    timestamp number(19,0) not null,
    primary key (id)
)
other stuff 

other stuff

应该只输出这个

create table a_table1 (
    id number(10,0) not null,
    timestamp number(19,0) not null,
    primary key (id)
)
create table a_table2 (
    id number(10,0) not null,
    primary key (id)
)

目前我正在使用 LineReader 并记住何时看到 create table 然后读取所有内容直到看到 )

这是最有效的方法吗?我可以使用一些花哨的 reg ex 吗?

我尝试了以下 reg ex 但这没有用,因为它只是再次返回整个字符串。也许新线路正在打破它

"^.*create.*a_(.*?)\\).*$", "$1")

如有任何建议,我们将不胜感激

谢谢

最佳答案

尝试这样的事情:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    IOUtils.copyLarge(getClass().getClassLoader().getResourceAsStream("input.txt"), baos);
    String org = baos.toString();

    final Pattern compile = Pattern.compile("(?s)(create table a_.*?\n\\)\n)");
    final Matcher matcher = compile.matcher(org);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }

输入.txt

Other stuff:

Other stuff:
create table a_table1 (
    id number(10,0) not null,
    timestamp number(19,0) not null,
    primary key (id)
)
stuff
create table a_table2 (
    id number(10,0) not null,
    primary key (id)
)

Other stuff:
create table b_table1 (
    id number(10,0) not null,
    timestamp number(19,0) not null,
    primary key (id)
)
other stuff

输出

create table a_table1 (
    id number(10,0) not null,
    timestamp number(19,0) not null,
    primary key (id)
)
create table a_table2 (
    id number(10,0) not null,
    primary key (id)
)

关于java - 用于读取 'create table' sql 语句的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14127247/

相关文章:

java - Netbeans 中具有多个可执行文件管理的软件

java - java中检查括号是否正确的问题

javascript - 在正则表达式中应用最大和最小限制

regex - 正则表达式不起作用

Java正则表达式特殊字符

java - 多人 2D 游戏中的数据结构 (Java)

java - 使用 Scanner 读取文本文件并计算每次出现的字母

java - 查询在 java 中创建单独的线程?

Javascript 正则表达式替换文本 div 和 < >

java - 正则表达式:忽略字符前后的空格