Groovy如何访问循环内部定义的变量?
解决Groovy中循环内部变量的访问问题
这个错误是典型的变量作用域问题——你在if代码块内部定义的nodePort,作用域只限于那个块,外面的println根本看不到它。下面给你几种解决思路,根据你的需求选就行:
方案1:提前在外部定义变量(适合只需要最后一个匹配值的场景)
把nodePort的定义移到循环和if块外面,这样内部的赋值操作能被外部访问到。如果有多行匹配nodePort:,最后一次赋值会覆盖之前的结果:
String nodePort = null fileContents.split('\n').each { if (it =~ /nodePort:/) { def splitted_string = it.split(':') nodePort = splitted_string[1].trim() } } println nodePort
方案2:用集合收集所有匹配值(适合需要所有结果的场景)
如果文件里有多行包含nodePort:,可以用List来收集所有匹配的端口值:
List<String> nodePorts = [] fileContents.split('\n').each { if (it =~ /nodePort:/) { def splitted_string = it.split(':') nodePorts.add(splitted_string[1].trim()) } } println nodePorts // 会打印所有匹配到的端口列表
方案3:用Groovy风格的简化写法(更简洁)
Groovy提供了很多便捷的集合方法,能让代码更简洁:
只获取第一个匹配的端口
用find找到第一行匹配的内容,再链式处理拆分和去空格,安全导航符?.能避免找不到匹配时抛出空指针:
def nodePort = fileContents.split('\n') .find { it =~ /nodePort:/ } ?.split(':') ?.[1] ?.trim() println nodePort
获取所有匹配的端口
用findAll筛选所有匹配行,再用collect提取端口值:
def nodePorts = fileContents.split('\n') .findAll { it =~ /nodePort:/ } .collect { it.split(':')[1].trim() } println nodePorts
内容的提问来源于stack exchange,提问作者IT-Sheriff
相关产品推荐
相关产品推荐

