微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Groovy无法从文本文件中捕获所需的字符串-Jmeter JSR223

如何解决使用Groovy无法从文本文件中捕获所需的字符串-Jmeter JSR223

我需要解析一个文本文件testresults.txt并捕获序列号,然后使用groovy Jmeter JSR223后处理器将捕获的序列号写到另一个名为serialno.txt的文本文件中。 下面的代码不起作用。它没有进入while循环本身。请帮助。

import java.util.regex.Pattern
import java.util.regex.Matcher

String filecontent = new File("C:/device/resources/testresults.txt").text

def regex = "SerialNumber\" value=\"(.+)\""

java.util.regex.Pattern p = java.util.regex.Pattern.compile(regex)
java.util.regex.Matcher m = p.matcher(filecontent)

File SN = new File("C:/device/resources/serialno.txt")

while(m.find()) {
     SN.write m.group(1) 
}

解决方法

如果您的代码没有进入循环,则意味着没有匹配项,因此您需要修改正则表达式,可以使用Regex101网站进行实验

给出testresults.txt文件的以下内容:

SerialNumber" value="foo"
SerialNumber" value="bar"
SerialNumber" value="baz"

您的代码可以正常工作。

目前,我只能建议使用match operator使您的代码更“时髦”

def source = new File('C:/device/resources/testresults.txt').text

def matches = (source =~ 'SerialNumber" value="(.+?)"')

matches.each { match ->
    new File('C:/device/resources/serialno.txt') << match[1] << System.getProperty('line.separator')
}

演示:

enter image description here

更多信息:Apache Groovy - Why and How You Should Use It

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。