求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
Whereclause 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. Matchesreturns all valid segments, which we cast toMatchobjects, 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

