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

如何用多种分隔符将字符串分割为List?附具体实例需求

多分隔符字符串分割实现方案

Python 实现

直接用正则表达式的re.split()方法,指定=和;作为分隔符:

import re

s = "Pesho=11;Gosho=4"
result = re.split(r'[=;]', s)
# 结果为 ['Pesho', '11', 'Gosho', '4']

[=;]是正则字符集,会匹配这两个符号中的任意一个,直接将字符串拆分成目标列表。

Java 实现

用String.split()传入正则表达式[=;]完成拆分,再转成List:

import java.util.Arrays;
import java.util.List;

public class SplitDemo {
    public static void main(String[] args) {
        String s = "Pesho=11;Gosho=4";
        String[] splitArr = s.split("[=;]");
        List<String> resultList = Arrays.asList(splitArr);
        // 结果为 [Pesho, 11, Gosho, 4]
    }
}

如果需要可变长度的List,可替换为new ArrayList<>(Arrays.asList(splitArr))。

C# 实现

有两种简单实现方式:

方式一:String.Split

直接指定分隔符数组,再转成List:

using System.Collections.Generic;
using System.Linq;

string s = "Pesho=11;Gosho=4";
char[] separators = { '=', ';' };
List<string> result = s.Split(separators).ToList();
// 结果为 [Pesho, 11, Gosho, 4]

若担心出现空元素,可添加StringSplitOptions.RemoveEmptyEntries参数增强鲁棒性。

方式二:Regex.Split

用正则匹配分隔符完成拆分:

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

string s = "Pesho=11;Gosho=4";
string[] splitArr = Regex.Split(s, "[=;]");
List<string> result = splitArr.ToList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:40:38