【问题标题】:How to read a snippet from a file using groovy?如何使用 groovy 从文件中读取片段?
【发布时间】:2009-09-29 12:20:07
【问题描述】:

我正在使用这个简单的示例代码在 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;

所以我想读一个sn-p。 如果我看到一行带有 rowid 的行,最后也有一个“分号”。然后我想读回'(select'

所以在阅读了这个文件后,我想要一个包含:

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

这可能吗?以及如何?

【问题讨论】:

    标签: groovy filereader


    【解决方案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;
    

    【讨论】:

    • 谢谢!那个正则表达式看起来很有趣,但它对我不起作用。在您的 test.txt 文件中,您的数据是分行还是一行?
    • @Drake:它们都在不同的行上。当输入是没有换行符的字符串时,它仍然有效(输出:'(Select * from some table where something = something) on rowid = something;')。作为记录:我使用的是 Groovy 1.6
    • ...但是如果输入文件中没有换行符,我会稍微改变我的正则表达式:在这种情况下没有贪婪的 DOT-STARS!
    【解决方案2】:

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

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

    【讨论】:

    猜你喜欢
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2022-11-04
    相关资源
    最近更新 更多