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

求C#实现按分隔符提取字符串并转为字符串数组的函数

Split String by Double Underscores into Clean Array in C#

Looks like you need to split a string by double underscores (__) while ignoring any empty entries from leading/trailing delimiters. Here are a couple of solid C# implementations using Linq and regex, which you mentioned:

Approach 1: String.Split + Linq

This is a straightforward, readable approach—split the string on the double underscore delimiter, then filter out any empty strings that might come from leading or trailing __.

using System.Linq;

public static string[] SplitByDoubleUnderscore(string input)
{
    // Split on "__" delimiter, then remove empty/null entries
    return input.Split(new[] {"__"}, StringSplitOptions.None)
                .Where(s => !string.IsNullOrEmpty(s))
                .ToArray();
}

How it works:

  • Split(new[] {"__"}, StringSplitOptions.None) splits the input at every occurrence of __, preserving empty strings (which we’ll filter out next).
  • The Where clause removes any empty or null strings from the split result.
  • ToArray() converts the filtered Linq sequence into a string array.

Testing this with your example input "str1__value__xyz__str4__" will return exactly {"str1", "value", "xyz", "str4"}.

Approach 2: Regular Expressions

If you prefer using regex, you can either split with a regex pattern or directly match all valid segments. Here’s a clean way to match segments directly:

using System.Text.RegularExpressions;
using System.Linq;

public static string[] SplitByDoubleUnderscoreWithRegex(string input)
{
    // Match all valid segments between/around "__" delimiters
    return Regex.Matches(input, @"(?<=^|__).+?(?=__|$)")
                .Cast<Match>()
                .Select(match => match.Value)
                .Where(s => !string.IsNullOrEmpty(s))
                .ToArray();
}

How it works:

  • The regex (?<=^|__).+?(?=__|$) uses positive lookbehind and lookahead to target segments that sit between __ delimiters, at the start of the string, or at the end.
  • Matches returns all valid segments, which we cast to Match objects, extract their values, filter out empty entries, and convert to an array.

A simpler regex alternative (mirroring the first approach) uses Regex.Split:

return Regex.Split(input, @"__")
            .Where(s => !string.IsNullOrEmpty(s))
            .ToArray();

Key Notes:

  • Both approaches handle edge cases like leading/trailing __ (e.g., "__test__hello__" becomes {"test", "hello"}) and elements with single underscores (e.g., "my_str__your_val__" returns {"my_str", "your_val"}).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:24:08