C# 带多个分隔符的条件拆分字符串
我有一根绳子C# 带多个分隔符的条件拆分字符串,c#,asp.net,string,delimiter,C#,Asp.net,String,Delimiter,我有一根绳子 string astring=“#这是一个部分*这是第一类*这是 第二类#这是另一部分”; 我想根据分隔符分隔这个字符串。如果在开始处有#,则表示节字符串(字符串[]节)。如果字符串以*开头,则表示我有一个类别(字符串[]类别)。 因此,我想 string[] section = { "This is a Section", "This is another Section" }; string[] category = { "This is the first categor
string astring=“#这是一个部分*这是第一类*这是
第二类#这是另一部分”;
我想根据分隔符分隔这个字符串。如果在开始处有#,则表示节字符串(字符串[]节)。如果字符串以*开头,则表示我有一个类别(字符串[]类别)。
因此,我想
string[] section = { "This is a Section", "This is another Section" };
string[] category = { "This is the first category ",
"This is the second Category " };
我找到了这个答案:
但这并不是我想要做的。使用string.Split可以做到这一点(比regex;)更快)
List sectionsResult=newlist();
列表类别结果=新列表();
字符串astring=“#这是一个部分*这是第一个类别*这是第二个类别#这是另一个部分”;
var sections=astring.Split('#')。其中(i=>!String.IsNullOrEmpty(i));
foreach(节中的var节)
{
var sectieandcategoris=section.Split('*');
sectionsResult.Add(sectieandcategoris.First());
categorysResult.AddRange(sectieandcategorys.Skip(1));
}
string astring=@“#这是一节*这是第一节*这是第二节#这是另一节”;
string[]sections=Regex.Matches(astring,@“#([^\*#]*)”).Cast()
.Select(m=>m.Groups[1].Value).ToArray();
string[]categories=Regex.Matches(astring,@“\*([^\*\\\\\\]*)”).Cast()
.Select(m=>m.Groups[1].Value).ToArray();
在我看来,这就像是一个正则表达式的工作,它使用的捕获组应该是在park@SimonRapilly你甚至不需要捕捉群组。匹配就足够了。没错,如果你的答案中有两个类似的正则表达式,但是如果你想要一个正则表达式,那么你需要捕获一个组。我犯了一个错误“string不包含拆分的定义”,这是一个很好的解决方案
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));
}
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();