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

如何从形如(数值,数值 | 数值)的字符串中提取指定内容?

字符串内容提取方案

结构分析

原字符串统一为 "(A,B | C)" 格式,需要提取的是逗号分隔的A,B和单独的C两部分内容。

实现思路

用正则表达式精准匹配目标内容,核心正则为:r'\((.*?) \| (.*?)\)',各部分含义:

  • \(:匹配字符串开头的左括号
  • (.*?):非贪婪匹配,捕获|前的所有内容(即A,B部分)
  • \|:匹配分隔用的竖线(需转义)
  • 第二个(.*?):捕获竖线到右括号之间的内容(即C部分)

代码示例(以Dart为例)

// 定义正则表达式
RegExp pattern = RegExp(r'\((.*?) \| (.*?)\)');

// 处理hello变量
String? hello = "(1.2,1.5 | 5)";
Match? helloMatch = pattern.firstMatch(hello!);
if (helloMatch != null) {
  var newhello1 = helloMatch.group(1); // 结果:1.2,1.5
  var newhello2 = helloMatch.group(2); // 结果:5
}

// 处理hi变量
String? hi = "(2.3,3.2 | 9)";
Match? hiMatch = pattern.firstMatch(hi!);
if (hiMatch != null) {
  var newhi1 = hiMatch.group(1); // 结果:2.3,3.2
  var newhi2 = hiMatch.group(2); // 结果:9
}

补充说明

  • 非贪婪匹配.*?确保只捕获到|和右括号前的内容,避免多余匹配
  • 若使用其他编程语言,正则逻辑完全一致,仅需调整对应语言的字符串匹配API即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:54:36