Groovy regex match list from readlines ()
I am trying to read a text file and return all lines that do not start with C #. In python, I could easily use a list to compose a 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 do the same through Groovy. As long as I have the code below, any help is greatly appreciated.
lines = new File("file.txt").readLines().findAll({x -> x ==~ /^#/ })
+3
source to share
1 answer
In groovy, you usually need to use collect
list comprehension instead. For example:
new File("file.txt").readLines().findAll({x -> x ==~ /^#/ }).
collect { it.replaceAll('\n', '') }
Note that it readLines()
already disables newlines, so this is not necessary in this case.
For searching, you can also use the method grep()
:
new File('file.txt').readLines().grep(~/^#.*/)
+4
source to share