【问题标题】:Split string start and end character拆分字符串开始和结束字符
【发布时间】:2018-11-14 01:55:34
【问题描述】:

例如,我有这个字符串:

string myString="abc {string 1} def {string 2}{string 3}";

我需要得到一个字符串数组:

string 1
string 2
string 3

{string 1}
{string 2}
{string 3}

有什么简单的方法吗?

【问题讨论】:

  • 你可以试试regex
  • 一个简单的正则表达式就可以了。到目前为止,您尝试过什么?
  • Regex 可能会比拆分更好
  • regex101.com 将帮助您学习正则表达式并为您的案例构建表达式

标签: c# arrays string split


【解决方案1】:

使用正则表达式。这是您想要执行的搜索:

{.+?}

例如:

    string input = "abc {string 1} def {string 2}{string 3}";
    string pattern = "{.+?}";
    Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);

    MatchCollection matches = rgx.Matches(input);
    if (matches.Count > 0)
    {
        Console.WriteLine("{0} ({1} matches):", input, matches.Count);
        foreach (Match match in matches)
            Console.WriteLine("   " + match.Value);
    }

产量

abc {string 1} def {string 2}{string 3} (3 matches):
   {string 1}
   {string 2}
   {string 3}

【讨论】:

  • 不需要所有这些捕获组,只需使用{.+?}(?<={).+?(?=}) 在匹配中不包含花括号。
  • 感谢您的反馈,您的建议是一种改进
【解决方案2】:

这是一个 LINQ 解决方案:

string myString="abc {string 1} def {string 2}{string 3}";

string[] result = myString.Split('{')
                          .Where(x => x.Contains("}"))
                          .Select(x => new string(x.TakeWhile(c => c != '}').ToArray()))
                          .ToArray();

结果:

result[0]="string 1"

result[1]="string 2"

result[2]="string 3"

DEMO HERE

【讨论】:

    猜你喜欢
    • 2020-10-19
    • 1970-01-01
    • 2020-10-22
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 2023-03-28
    相关资源
    最近更新 更多