This question already has an answer here:
这个问题在这里已有答案:
- C# Regex Split - commas outside quotes 5 answers
- C#Regex Split - 逗号外引用5个答案
I need to separate the following string by comma and get the chunks down below. What's the most elegant solution in C#? String.Split() detects also internal commas, of course.
我需要用逗号分隔以下字符串并在下面获取块。什么是C#中最优雅的解决方案?当然,String.Split()还会检测内部逗号。
"'_82X5_00_11 (2,RAL 7035)', '_82X5_00_11 (2,RAL 7035)', #349, #1 "
The result should be:
结果应该是:
'_82X5_00_11 (2,RAL 7035)'
'_82X5_00_11 (2,RAL 7035)'
#349
#1
Thanks.
谢谢。
1 个解决方案
#1
0
Try this:
尝试这个:
string aux = "'_82X5_00_11 (2,RAL 7035)', '_82X5_00_11 (2,RAL 7035)', #349, #1 ";
var result = Regex.Split(aux, ("(?!\\B'[^']*),(?![^']*'\\B)"));
EDIT
编辑
This was not getting the " '', '' "
because '' doesn't contain anything.
这不是“'',''”,因为''不包含任何内容。
Solution:
解:
string pattern = "('[^']+'|[^',^\\s]+|['']+)";
string str1 = "'_82X5_00_11 (2,RAL 7035)', '_82X5_00_11 (2,RAL 7035)', #349, #1 ";
string str2 = "'', '', #344, #334";
var result1 = Regex.Matches(str1, pattern).Cast<Match>().Select(x => x.Value).ToArray();
var result2 = Regex.Matches(str2, pattern).Cast<Match>().Select(x => x.Value).ToArray();
#1
0
Try this:
尝试这个:
string aux = "'_82X5_00_11 (2,RAL 7035)', '_82X5_00_11 (2,RAL 7035)', #349, #1 ";
var result = Regex.Split(aux, ("(?!\\B'[^']*),(?![^']*'\\B)"));
EDIT
编辑
This was not getting the " '', '' "
because '' doesn't contain anything.
这不是“'',''”,因为''不包含任何内容。
Solution:
解:
string pattern = "('[^']+'|[^',^\\s]+|['']+)";
string str1 = "'_82X5_00_11 (2,RAL 7035)', '_82X5_00_11 (2,RAL 7035)', #349, #1 ";
string str2 = "'', '', #344, #334";
var result1 = Regex.Matches(str1, pattern).Cast<Match>().Select(x => x.Value).ToArray();
var result2 = Regex.Matches(str2, pattern).Cast<Match>().Select(x => x.Value).ToArray();