我想使用分隔字符分割字符串数组,但引号之间的字符除外
本文关键字:字符 之间 数组 分隔 字符串 分割 | 更新日期: 2023-09-27 18:05:40
下面是我的代码,使用分隔字符分割字符串数组,但不考虑标题中的问题:
char[] delimitedChars = { ',', ''n', '"' };
words = stringamabob.Split(delimitedChars);
我希望这些都为真,除非我不希望逗号在引号之间是分隔符。
例如,如果我有:
stringamabob = 1, 2, 3, " 4, 5 ", 6
我将得到:words [0] = one
words [1] = two
words [2] = three
words [3] = 4
words [4] = five
words [5] = 6
Where as I want get:
words [0] = one
words [1] = two
words [2] = three
words [3] = four, five
words [4] = 6
试试这个,如果你有引号嵌套在彼此之间(这种情况很少见),它将不起作用,但它应该在所有其他情况下工作。
string[] quotesplit = stringamabob.Split('"'); //Split by quotes.
char[] delimitedChars = { ',', ''n'}; //remove quotes from these delimiters because we've already split by them
List<string> words = new List<string>();
bool toggle = stringamabob.StartsWith("'""); //check if the first item is quoted
foreach(string chunk in quotesplit)
{
if(toggle) //toggle is true when we're not inside quotes
{
words.AddRange(chunk.Split(delimitedChars));
}
else
{
words.Add(chunk);
}
toggle = !toggle;
}
像这样的正则表达式似乎可以工作:
"(.*)"|('S*),|('S*)$
如图
所示您将在第一组(引号)或第二组(逗号)或第三组(行尾)中找到匹配项