来自readlines()的Groovy正则表达式匹配列表

Chr*_*ell 4 regex groovy readlines

我试图读取一个文本文件并返回所有不以#开头的行.在python中我可以轻松使用列表理解列表

with open('file.txt') as f:
     lines = [l.strip('\n') for l in f.readlines() if not re.search(r"^#", l)]
Run Code Online (Sandbox Code Playgroud)

我想通过Groovy完成同样的事情.到目前为止,我有以下代码,非常感谢任何帮助.

lines = new File("file.txt").readLines().findAll({x -> x ==~ /^#/ })
Run Code Online (Sandbox Code Playgroud)

ata*_*lor 5

在groovy中,通常必须使用collect代替列表推导.例如:

new File("file.txt").readLines().findAll({x -> x ==~ /^#/ }).
    collect { it.replaceAll('\n', '') }
Run Code Online (Sandbox Code Playgroud)

请注意,readLines()已经剥离换行符,因此在这种情况下没有必要.

对于搜索,您还可以使用以下grep()方法:

new File('file.txt').readLines().grep(~/^#.*/)
Run Code Online (Sandbox Code Playgroud)