我需要在 C# 中用 ',' 拆分这段代码。
示例字符串:
'DC0''008_','23802.76','23802.76','23802.76','Comm,erc,','2f17','3f44c0ba-daf1-44f0-a361-'
我可以使用 string.split(',') 但如您所见,'Comm,erc,' 被分割为
comm
erc
'DC0''008_' 也应该拆分为
'DC0''008_'
不像
'DC0'
'008_'
预期的输出应该是这样的:
'DC0''008_'
'23802.76'
'23802.76'
'23802.76'
'Comm,erc,'
'2f17'
'3f44c0ba-daf1-44f0-a361-'
最佳答案
split
可以做到,但正则表达式会更复杂。
您可以使用 Regex.Matches
使用这个更简单的正则表达式:
'[^']*'
并获取集合中所有带引号的字符串。
代码:
MatchCollection matches = Regex.Matches(input, @"'[^']*'");
打印所有匹配的值:
foreach (Match match in Regex.Matches(input, @"'[^']*'"))
Console.WriteLine("Found {0}", match.Value);
将所有匹配值存储在 ArrayList
中:
ArrayList list = new ArrayList();
foreach (Match match in Regex.Matches(input, @"'[^']*'")) {
list.add(match.Value);
}
编辑:如果 OP 想要使用 ''
,请按照下面的评论在捕获的字符串中然后使用此环视正则表达式:
'.*?(?<!')'(?!')
(?<!')'(?!')
表示匹配未被另一个单引号包围的单引号。
关于c# - 在 C# 中按字符拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40416135/