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

如何从斜杠分隔颜色的字符串中提取颜色值并生成数组

提取字符串中的颜色值并转为数组的实现方法

没问题,我来给你拆解这个需求——从类似 Color of model: White/White/White 这样的字符串里提取所有颜色值,不管数量多少,转成数组。下面给你几个常用编程语言的实现方法:

JavaScript 实现

核心思路是先把冒号后面的颜色部分截取出来,再用斜杠/分割成数组,还可以顺便处理掉可能存在的空格:

const str = "Color of model: White/White/White";
// 先截取冒号后的部分,去除前后空格,再按斜杠分割
const colorArray = str.split(':')[1].trim().split('/');
// 如果颜色值前后有空格,还可以进一步处理
const cleanedColorArray = colorArray.map(color => color.trim());
console.log(cleanedColorArray); // 输出: ["White", "White", "White"]

Python 实现

Python的字符串处理同样简洁,步骤和JS类似:

str_input = "Color of model: White/White/White"
# 分割冒号,取第二部分,去除前后空格后按斜杠分割
color_list = str_input.split(':')[1].strip().split('/')
# 处理颜色值可能的空格
cleaned_color_list = [color.strip() for color in color_list]
print(cleaned_color_list) # 输出: ['White', 'White', 'White']

Java 实现

Java里可以用split方法完成,注意处理字符串索引的安全性:

public class ColorExtractor {
    public static void main(String[] args) {
        String str = "Color of model: White/White/White";
        // 分割冒号,确保数组长度足够
        String[] parts = str.split(":");
        if (parts.length >= 2) {
            // 提取颜色部分并分割
            String[] colorArray = parts[1].trim().split("/");
            // 清理每个颜色的空格
            for (int i = 0; i < colorArray.length; i++) {
                colorArray[i] = colorArray[i].trim();
            }
            // 输出结果
            for (String color : colorArray) {
                System.out.println(color);
            }
        }
    }
}

额外说明

如果你的字符串格式有变动(比如冒号前后有多个空格),上面的代码也能适配,因为我们用了trim()/strip()来清理多余空格;不管颜色数量是2个、4个还是更多,split('/')都会自动把所有颜色拆分成数组元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:49:04