如何解析一个逗号分隔字符串时,逗号和括号现场存在 [英] How to parse a comma delimited string when comma and parenthesis exists in field
本文介绍了如何解析一个逗号分隔字符串时,逗号和括号现场存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个字符串在C#
adj_con(CL2,1,3,0),adj_cont(CL1,1, 3,0),NG,NG / CL,5值CL(JK)中,HO
我要使用正则表达式来解析它来获得以下内容:
adj_con(CL2,1,3,0)
adj_cont(CL1,1,3,0)
NG
NG / CL
5值CL(JK)
HO
的
除了上面的例子中,我用下面的测试,但我仍然无法正确解析它。
%exc.uns:8小时让@ = ABC,DEF,exc_it = 1天,SUMM = graffe,A,b,(C ,D)
新文本将在一个字符串
字符串myStr的= @%exc.uns:8小时让@ = ABC,DEF,exc_it = 1天,SUMM = graffe,A,b,(C,D);
解决方案
字符串str =adj_con(CL2,1,3,0),adj_cont(CL1,1,3,0),NG,NG / CL,5值CL(JK)中,HO;
变种resultStrings =新的List<串GT;();
诠释? firstIndex = NULL;
INT scopeLevel = 0;
的for(int i = 0; I< str.Length;我++)
{
如果(STR [I] ==','和;&安培; scopeLevel == 0)
{
resultStrings.Add(str.Substring(firstIndex.GetValueOrDefault(),我 - firstIndex.GetValueOrDefault()));
firstIndex = I + 1;
}
,否则如果(STR [I] =='(')scopeLevel ++;
,否则如果(STR [I] ==')')scopeLevel--;
}
resultStrings.Add(str.Substring(firstIndex.GetValueOrDefault()));
I have this string in C#
adj_con(CL2,1,3,0),adj_cont(CL1,1,3,0),NG, NG/CL, 5 value of CL(JK), HO
I want to use a RegEx to parse it to get the following:
adj_con(CL2,1,3,0)
adj_cont(CL1,1,3,0)
NG
NG/CL
5 value of CL(JK)
HO
In addition to the above example, I tested with the following, but am still unable to parse it correctly.
"%exc.uns: 8 hours let @ = ABC, DEF", "exc_it = 1 day" , " summ=graffe ", " a,b,(c,d)"
The new text will be in one string
string mystr = @"""%exc.uns: 8 hours let @ = ABC, DEF"", ""exc_it = 1 day"" , "" summ=graffe "", "" a,b,(c,d)""";
解决方案
string str = "adj_con(CL2,1,3,0),adj_cont(CL1,1,3,0),NG, NG/CL, 5 value of CL(JK), HO";
var resultStrings = new List<string>();
int? firstIndex = null;
int scopeLevel = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ',' && scopeLevel == 0)
{
resultStrings.Add(str.Substring(firstIndex.GetValueOrDefault(), i - firstIndex.GetValueOrDefault()));
firstIndex = i + 1;
}
else if (str[i] == '(') scopeLevel++;
else if (str[i] == ')') scopeLevel--;
}
resultStrings.Add(str.Substring(firstIndex.GetValueOrDefault()));
这篇关于如何解析一个逗号分隔字符串时,逗号和括号现场存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文