【问题标题】:How to split text using certain delimitation如何使用特定分隔符分割文本
【发布时间】:2019-02-26 00:25:13
【问题描述】:

我有当前的场景

string b = "{Lorem ipsum dolor} sit amet, consectetur adipiscing elit, 
Ut enim adminim veniam, quis {nostrud exercitation};

我想这样拆分字符串 b:

   string[] splittedString = new string[] {
  "{Lorem ipsum dolor}",
  "sit amet, consectetur adipiscing elit, Ut enim ad minim veniam, quis", 
  "{nostrud exercitation}" };

如何使用正则表达式实现这一点?

【问题讨论】:

  • 你要在逗号上分开
  • 文本是动态的,可以不带逗号,分隔符为{any value inside}
  • 挑选{text goes here} 部分很容易(只需使用组)。挑选出没有分隔符的部分会更难。您可能需要挑选出这些组,然后再进行第二次通过并拾取您留下的部分
  • 你可以使用 regex.split
  • b.split(new [] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries) 将为您提供不带任何花括号的零件。

标签: c# arrays .net regex string


【解决方案1】:

这是一个使用正则表达式的快速而简单的解决方案。它还处理第一个 { 之前和/或最后一个 ] 之后有文本的情况。

首先是正则表达式和要解析的字符串:

//Regex: get things that start with a {, followed by one or more non-} characters, followed by a } 
private const string Pattern = @"(\{[^\}]+\})";
private const string TheText = "{Lorem ipsum dolor} sit amet, consectetur adipiscing elit, Ut enim adminim veniam, quis {nostrud exercitation}";

然后是一些代码:

 var regex = new Regex(Pattern);
 var matches = regex.Matches(TheText);
 var results = new List<string>();
 var currentIndex = 0;
 foreach (var match in matches.Cast<Match>())
 {
     var lastIndex = currentIndex;
     //pickup any undelimited text at the beginning or between delimited groups
     if (match.Index != currentIndex)
     {
         var unDelimited = TheText.Substring(currentIndex, match.Index - lastIndex);
         results.Add(unDelimited);
         currentIndex += unDelimited.Length;
     }
     results.Add(match.Groups[0].ToString());
     currentIndex += match.Length;
 }

 //finally pickup any undelimited text at the end
 if (TheText.Length > currentIndex)
 {
     results.Add(TheText.Substring(currentIndex));
 }

它依靠正则表达式来查找每个{some text here} 匹配项。然后遍历这些匹配项,直接从匹配项或从原始字符串的子字符串(使用匹配项的位置信息)创建一个列表。

我还用如下字符串对其进行了测试:

private const string TheText = "before {first} middle {second} after";

最后,我的代码在未定界的文本中保留任何前导或尾随空格。你可以摆脱那些string.Trim

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    相关资源
    最近更新 更多