【问题标题】:Conditional Split String with multiple delimiters具有多个分隔符的条件拆分字符串
【发布时间】:2013-08-06 10:06:11
【问题描述】:

我有一个字符串

string astring="#This is a Section*This is the first category*This is the
second Category# This is another Section";

我想根据分隔符分隔这个字符串。如果我在开头有 # 这将指示部分字符串(字符串 [] 部分)。如果字符串以 * 开头,这将表明我有一个类别(字符串 [] 类别)。 结果我想拥有

string[] section = { "This is a Section", "This is another Section" }; 
string[] category = { "This is the first category ",
     "This is the second Category " };

我找到了这个答案: string.split - by multiple character delimiter 但这不是我想要做的。

【问题讨论】:

  • 对我来说看起来像是正则表达式的工作,使用捕获应该在公园散步的组
  • @SimonRapilly 你甚至不需要捕获组。匹配就足够了。
  • 确实如此,如果您的答案中有两个正则表达式,但如果您想要一个正则表达式,那么您将需要捕获组

标签: c# asp.net string delimiter


【解决方案1】:
string astring=@"#This is a Section*This is the first category*This is the second Category# This is another Section";

string[] sections = Regex.Matches(astring, @"#([^\*#]*)").Cast<Match>()
    .Select(m => m.Groups[1].Value).ToArray();
string[] categories = Regex.Matches(astring, @"\*([^\*#]*)").Cast<Match>()
    .Select(m => m.Groups[1].Value).ToArray();

【讨论】:

  • 感谢您的出色解决方案
【解决方案2】:

使用 string.Split 你可以做到这一点(比正则表达式更快;))

List<string> sectionsResult = new List<string>();
List<string> categorysResult = new List<string>();
string astring="#This is a Section*This is the first category*This is thesecond Category# This is another Section";

var sections = astring.Split('#').Where(i=> !String.IsNullOrEmpty(i));

foreach (var section in sections)
{
    var sectieandcategorys =  section.Split('*');
    sectionsResult.Add(sectieandcategorys.First());
    categorysResult.AddRange(sectieandcategorys.Skip(1));
}

【讨论】:

  • 我收到错误“字符串不包含拆分定义”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-29
相关资源
最近更新 更多