Dart中如何从RGB格式字符串中提取R、G、B三个通道的数值?
Dart 正则提取RGB颜色分量的正确方法
你使用allMatches方法得到的是匹配结果的迭代器,需要先取出对应的匹配项再访问分组捕获的内容,具体实现如下:
方法1:使用allMatches(适配多匹配场景)
RegExp rgb = RegExp(r"^rgb\(([0-9]+),\s*([0-9]+),\s*([0-9]+)\)$"); final matches = rgb.allMatches("rgb(127, 127, 126)"); if (matches.isNotEmpty) { final matchItem = matches.first; // 分组索引从1开始,0为完整匹配的字符串 int r = int.parse(matchItem.group(1)!); int g = int.parse(matchItem.group(2)!); int b = int.parse(matchItem.group(3)!); // 输出示例:R:127, G:127, B:126 print('R:$r, G:$g, B:$b'); }
方法2:使用firstMatch(单匹配场景更简洁,和JS的exec逻辑更接近)
如果只需要匹配一次,不需要处理多个匹配结果,直接用firstMatch更合适:
RegExp rgb = RegExp(r"^rgb\(([0-9]+),\s*([0-9]+),\s*([0-9]+)\)$"); final match = rgb.firstMatch("rgb(127, 127, 126)"); if (match != null) { // 也可以用下标语法直接访问分组,和数组访问逻辑一致 int r = int.parse(match[1]!); int g = int.parse(match[2]!); int b = int.parse(match[3]!); }
逻辑说明
Dart的正则匹配结果封装为RegExpMatch对象,和JS中exec返回的数组逻辑对应:
- 索引/分组
0对应完整匹配的整个字符串 - 索引/分组
1~n对应正则中从左到右的捕获括号内容
内容的提问来源于stack exchange,提问作者Ajit Kumar
相关产品推荐
相关产品推荐

