You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JMeter BeanShell后置处理器:正则提取值后随机选值存变量

解决JMeter BeanShell后置处理器随机选取提取值的问题

你的代码问题在于循环时每次都覆盖Depart_city变量,最终只保留最后一个提取的城市。要实现随机选值,需要先收集所有提取结果,再随机挑选:

修改后的代码

import java.util.Random;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;

// 获取响应数据
String responseData = prev.getResponseDataAsString();

// 正则匹配城市选项
Pattern pattern = Pattern.compile("<option value=\"(.+?)\">(.+?)</option>");
Matcher matcher = pattern.matcher(responseData);

// 创建列表存储所有提取的城市
ArrayList<String> cities = new ArrayList<>();

// 遍历匹配结果,存入列表
while(matcher.find()) {
    String cityCode = matcher.group(1);
    cities.add(cityCode);
    log.info("提取到城市编码: " + cityCode);
}

// 如果列表不为空,随机选一个存入变量
if(!cities.isEmpty()) {
    Random random = new Random();
    int randomIndex = random.nextInt(cities.size());
    String randomCity = cities.get(randomIndex);
    vars.put("Depart_city", randomCity);
    log.info("随机选中的城市编码: " + randomCity);
} else {
    log.warn("未提取到任何城市数据");
}

关键改动说明

  • 新增ArrayList<String> cities用于存储所有提取到的城市编码,避免变量被覆盖
  • 循环时将每个匹配到的matcher.group(1)添加到列表中
  • 循环结束后,通过Random.nextInt(cities.size())生成随机索引,从列表中取出对应值存入Depart_city变量
  • 增加了空列表判断,避免无数据时出现空指针异常

内容的提问来源于stack exchange,提问作者Rakesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 03:08:17