用正则表达式分割字符串(C#扩展方法)

本文介绍了一种C#中扩展String类的方法,该方法利用正则表达式来分割字符串,并可以选择是否包含匹配项。此扩展方法为String类的Split方法添加了新的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不多说了方法体如下:

public static class StringExtension
{
    /// <summary>
    /// String 扩充方法(用正则表达式分割字符串)
    /// </summary>
    /// <param name="target">目标字符串</param>
    /// <param name="regex">正则表达式</param>
    /// <param name="isIncludeMatch">是否包括匹配结果</param>
    /// <returns>数组</returns>
    public static string[] Split(this string target, Regex regex,bool isIncludeMatch=true)
    {
        List<string> list = new List<string>();
        MatchCollection mc = regex.Matches(target);
        int curPostion = 0;
        foreach (Match match in mc)
        {
            if (match.Index != curPostion)
            {
                list.Add(target.Substring(curPostion, match.Index - curPostion));
            }
            curPostion = match.Index + match.Length;
            if (isIncludeMatch)
            {
                list.Add(match.Value);
            }
        }
        if (target.Length > curPostion)
        {
            list.Add(target.Substring(curPostion));
        }
        return list.ToArray();
    }
}

此处相当于对string的Spli的方法添加了一个重载

关于C#扩充方法的语法和使用问题,请参考微软官方:

http://msdn.microsoft.com/zh-cn/library/bb383977


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值