gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:11:37 25 4
gpt4 key购买 nike

我正在尝试读取文本文件并返回所有不以 # 开头的行。在 python 中,我可以轻松地使用列表理解列表

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

我想通过 Groovy 完成同样的事情。到目前为止,我有以下代码,非常感谢任何帮助。
lines = new File("file.txt").readLines().findAll({x -> x ==~ /^#/ })

最佳答案

在groovy中,一般要使用collect代替列表理解。例如:

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

请注意 readLines()已经去掉了换行符,所以在这种情况下没有必要。

对于搜索,您还可以使用 grep()方法:
new File('file.txt').readLines().grep(~/^#.*/)

关于regex - 来自 readlines() 的 Groovy 正则表达式匹配列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14512867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com