1、这个问题根本用不着正则 2、就算是用正则,你的正则肯定是错的,跟回溯也扯不上关系string test = ",abc,df,ssd,dfdf,"; string[] result = test.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries); foreach (string s in result) { richTextBox2.Text += s + "\n"; }
try...string test = "sss,\"sdfdsf,sss\",df,ssss,\"ddd,dfdf\",\"df,gg\""; Regex reg = new Regex("\"(?<c>[^\"]+)\"|(?<c>[^,]+)"); MatchCollection mc = reg.Matches(test); foreach (Match m in mc) { richTextBox2.Text += m.Groups["c"].Value + "\n"; }
正则真的不用这么罗嗦 public string[] GetSplitNumber(string s) { Regex regex = new Regex(@"\b\w+\b"); MatchCollection mc = regex.Matches(s); List<string> ls = new List<string>(); foreach (Match m in mc) { ls.Add(m.Value); } return ls.ToArray(); }
2、就算是用正则,你的正则肯定是错的,跟回溯也扯不上关系string test = ",abc,df,ssd,dfdf,";
string[] result = test.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
{
richTextBox2.Text += s + "\n";
}
正则是(?!,)\w+(?<!,)
处理后结果: sss sdfdsf,sss df ssss ddd,dfdf df,gg
不知道有没有说明白
这是最 Biu 准的答案了
注意原字串前后空格要去掉
Regex reg = new Regex("\"(?<c>[^\"]+)\"|(?<c>[^,]+)");
MatchCollection mc = reg.Matches(test);
foreach (Match m in mc)
{
richTextBox2.Text += m.Groups["c"].Value + "\n";
}
public string[] GetSplitNumber(string s)
{
Regex regex = new Regex(@"\b\w+\b");
MatchCollection mc = regex.Matches(s);
List<string> ls = new List<string>();
foreach (Match m in mc)
{
ls.Add(m.Value);
}
return ls.ToArray();
}