如何拆分包含方括号和空格的字符串

时间:2021-05-08 16:38:11

标签: c# arrays string split format

我正在尝试拆分以下字符串:

"add galaxy [Milky way] elliptical 13.2B"

我想要实现的结果数组应包含以下字符串:

"add","galaxy","Milky way","eliptical","13.2B"

我尝试使用 string.Split() 并尝试使用不同的方法参数,但没有达到我想要的效果。

我怎样才能达到这个结果?

编辑: 我找到了一种使用正则表达式的方法。

@"[A-Za-z0-9.]+|(#.*?#)|(\[.*?\])"

2 个答案:

答案 0 :(得分:2)

这是一个快速而肮脏的解决方案。不考虑多个空格或多个嵌套 [[[]]] 的可能性。

string[] split(string s)
{
    List<string> list = new List<string>();
    int start = 0;
    int end = 0;
    bool inBlock = false;

    for(; end < s.Length; end++)
    {
        if (s[end] == '[')
        {
            inBlock = true;
            start++;
        }
        else if(s[end] == ']' && inBlock)
        {
            inBlock = false;
            list.Add(s.Substring(start, end - start));
            end++;
            start = end + 1;
        }
        else if(s[end] == ' ' && !inBlock)
        {
            list.Add(s.Substring(start, end - start));
            start = end + 1;
        }
    }
    if(end > start)
        list.Add(s.Substring(start, end - start));

    return list.ToArray();
}

答案 1 :(得分:0)

除了使用 split,您还可以使用 Regex.Matches

(?<=\[)[^][]+(?=])|(?<=#)[^#]+(?=#)|[A-Za-z0-9.]+

说明

  • (?<=\[)[^][]+(?=])在左侧断言 [,在右侧断言 ] 并匹配两者之间的所有内容
  • |
  • (?<=#)[^#]+(?=#) 向左断言 #,向右断言 # 并匹配中间的所有 o
  • |
  • [A-Za-z0-9.]+ 匹配 1+ 次字符类中列出的任何一个

查看 regex demoC# demo

例如

string pattern = @"(?<=\[)[^][]*(?=])|(?<=#)[^#]*(?=#)|[A-Za-z0-9.]+";
string input = @"add galaxy [Milky way] elliptical 13.2B #test test #";    
String[] matches = Regex.Matches(input, pattern)
           .Cast<Match>()
           .Select(m => m.Value)
           .ToArray();

foreach (String m in matches)
{
    Console.WriteLine(m);
}

输出

add
galaxy
Milky way
elliptical
13.2B
test test

如果您希望使用 Regex.Split 获得该结果,您可以在模式中使用捕获组(在外部 # 或方括号内)以在输出中保留分隔符并删除数组。

string pattern = @"([A-Za-z0-9.]+)|#([^#]+)#|\[([^][]+)]";
string input = @"add galaxy [Milky way] elliptical 13.2B #test test #";
string[] items = Regex.Split(input, pattern).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

foreach (string item in items)
{
    Console.WriteLine(item);
}

输出

add
galaxy
Milky way
elliptical
13.2B
test test

查看 regex demoC# demo