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

从ComboBox字符串中提取价格失败,现有代码误移除价格内容

问题分析与解决

你的代码逻辑完全搞反了:replaceAll("(\\d+(?:\\.\\d{1,2})?)", "")是把匹配到的价格数字替换为空字符串,所以输出的自然是去掉价格后的文本,和你要提取价格的需求正好相反。

正确实现方法

方法一:正则匹配提取(适合格式不固定的情况)

用Pattern和Matcher找到文本中的价格部分并提取:

String product = cboProduct.getSelectedItem().toString();
// 正则匹配整数或最多两位小数的价格
Pattern pricePattern = Pattern.compile("\\d+(?:\\.\\d{1,2})?");
Matcher matcher = pricePattern.matcher(product);

String price = "";
if (matcher.find()) {
    price = matcher.group(); // 获取匹配到的价格字符串
}

textareaOrder.setText(price);

方法二:字符串分割(适合格式固定的情况)

既然你的选项格式固定为“商品名: 价格”,直接按: 分割字符串取第二部分更简单:

String product = cboProduct.getSelectedItem().toString();
// 按": "分割成两部分
String[] splitParts = product.split(": ");
// 取分割后的第二个元素就是价格
String price = splitParts[1];

textareaOrder.setText(price);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:32:37