Chris Powell
Chris Powell

Reputation: 185

Groovy regex match list from readlines()

I am trying to read a text file and return all lines that do not begin with a #. In python I could easily use list comprehension list

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

I would like to accomplish the same thing via Groovy. So far I have the below code, any help is greatly appreciated.

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

Upvotes: 4

Views: 8809

Answers (1)

ataylor
ataylor

Reputation: 66059

In groovy, you generally have to use collect in place of list comprehensions. For example:

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

Note that readLines() already strips off newlines, so in this case it's not necessary.

For searching, you can also use the grep() method:

new File('file.txt').readLines().grep(~/^#.*/)

Upvotes: 5

Related Questions