如何使用groovy从文件中读取片段?

时间:2009-09-29 12:20:07

标签: groovy filereader

我正在使用这个简单的示例代码

在groovy中读取文件
file.eachLine {line->
 // do something with line
}

例如我的文件有一些这样的数据

blah blah blah 
This is some more lines
more lines
Insert into something
(x1,x2,x3)
(Select * from
some table
where 
something = something)
on rowid = something;

所以我想阅读一个片段。 如果我看到一行有rowid,那末尾也有一个'分号'。然后我想回读'(选择'

因此,在阅读此文件后,我想要一个包含以下内容的字符串:

(Select * from
    some table
    where 
    something = something)
    on rowid = something;

这可能吗?怎么样?

2 个答案:

答案 0 :(得分:1)

如果您的文件内容很小,那么很容易读取整个文件,然后使用一些正则表达式来获取您想要的部分:

def file = new File('/home/bart/Temp/test.txt')
def contents = file.getText()
def matcher = contents =~ /\(Select[^)]++\)\s++.*?rowid\s=\s.*;/
matcher.each { println it }

产地:

(Select * from
some table
where 
something = something)
on rowid = something;

答案 1 :(得分:0)

收集列表中的行,当您注意到“;”时,通过抛出异常来停止隐式循环。

您寻找的结果是从list.lastIndexOf('(select')到列表末尾的子列表。