C# 拆分字符串但不拆分分隔符,仅在[…]对之外
如何拆分字符串,使用“;”作为分隔符,但仅当此分隔符不在任何[…]内时。 e、 gC# 拆分字符串但不拆分分隔符,仅在[…]对之外,c#,split,C#,Split,如何拆分字符串,使用“;”作为分隔符,但仅当此分隔符不在任何[…]内时。 e、 g [a;b]c;d[e;f]=>[a;b]cd[e;f] A.Bc[e;f;g]=>abc[e;f;g] abcd[e;f]=>abcd[e;f] 这里有一种正则表达式方法,它使用一个负的前瞻性断言只有不嵌套在[…]中的分号才能用于拆分: string input = "[a;b]c;d[e;f]"; string[] parts = Regex.Split(input, @";(?![^\[]*\])"); f
[a;b]c;d[e;f]=>[a;b]cd[e;f]
A.Bc[e;f;g]=>abc[e;f;g]
abcd[e;f]=>abcd[e;f]
这里有一种正则表达式方法,它使用一个负的前瞻性断言只有不嵌套在[…]中的分号才能用于拆分:
string input = "[a;b]c;d[e;f]";
string[] parts = Regex.Split(input, @";(?![^\[]*\])");
foreach (string part in parts)
{
Console.WriteLine(part);
}
这张照片是:
[a;b]c
d[e;f]
下面是对所用正则表达式的解释:
; match a semicolon
(?![^\[]*\]) provided that we can look ahead and confirm that we CANNOT hit a closing ]
without first also hitting an opening [
如果断言为负前瞻,则表示分号不在[…]
内。请注意,我的回答假设您永远不会有嵌套的括号。如果你能做到这一点,你应该远离正则表达式,而应该考虑编写一个简单的解析器。 下面的代码将处理嵌套括号,并比正则表达式更快地工作。我已经为以下代码运行了100000次迭代,使用RegExp.Split()的代码的运行时间为322ms,而使用RegExp.Split()的代码为1116ms
List List_OutputStr=newlist();
int i_nestedbracketscont=0;
StringBuilder sb=新的StringBuilder();
foreach(s_InputStr中的字符)
{
如果(ch.Equals(“;”)&i_nestedBracketScont==0){list_OutputStr.Add(sb.ToString());sb.Clear();continue;}
如果(ch.Equals('['))i_nestedBracketScont++;
否则如果(ch.Equals(']')i_嵌套括号-;
某人附加(ch);
}
如果(sb.Length>0)list_OutputStr.Add(sb.ToString());
foreach(列表中的字符串str\u OutputStr)
Console.Write(str+“\t”);
您必须为此编写解析器我建议使用RegexThanks,但这是我的问题,如何拆分它?
; match a semicolon
(?![^\[]*\]) provided that we can look ahead and confirm that we CANNOT hit a closing ]
without first also hitting an opening [
List<string> list_OutputStr = new List<string>();
int i_NestedBracketsCount = 0;
StringBuilder sb = new StringBuilder();
foreach (char ch in s_InputStr)
{
if (ch.Equals(';') && i_NestedBracketsCount == 0) { list_OutputStr.Add(sb.ToString()); sb.Clear(); continue; }
else if (ch.Equals('[')) i_NestedBracketsCount++;
else if (ch.Equals(']')) i_NestedBracketsCount--;
sb.Append(ch);
}
if (sb.Length > 0) list_OutputStr.Add(sb.ToString());
foreach (string str in list_OutputStr)
Console.Write(str + "\t");