2

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

一个输入:

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)
)

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

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

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

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

任何意见,将不胜感激

谢谢

4

2 回答 2

3

尝试这样的事情:

    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)
)
于 2013-01-02T19:28:51.090 回答
3

只要在 create table sql 语句中只有 2 级括号嵌套,以下基于正则表达式的代码就可以工作:

String sql = "Other stuff: \n\nOther stuff: \ncreate table a_table1 (\nid number(10,0) not null,\ntimestamp number(19,0) not null,\nprimary key (id)\n)\nstuff\ncreate table a_table2 (\nid number(10,0) not null,\nprimary key (id)\n)\n\nOther stuff: \ncreate table b_table1 (\nid number(10,0) not null,\ntimestamp number(19,0) not null,\nprimary key (id)\n)\nother stuff \n\nother stuff\n\n";
Pattern p = Pattern.compile(
   "(?i)create\\s+table\\s+a_\\w+\\s+\\((?:[^()]+|\\([^()]+\\))*\\)"
);
Matcher m = p.matcher(sql);
while (m.find()) {
    System.out.println(m.group());
}

输出

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)
)
于 2013-01-02T19:53:28.523 回答