这是我倾向于实现的示例输入和输出格式。我在使用regex在线拆分的几个解决方案的工作,但它不满足所有条件。希望有人能提供帮助。我需要一个正则表达式分裂解决方案。请不要建议图书馆。谢谢。
List<string> values = new List<string>();
Regex lineSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);
foreach (Match match in lineSplit.Matches(line))
{
values.Add(match.Value.TrimStart(',').Replace("\"", ""));
}
"123","456","789"
123
456
789
"123"","456","789"
123"
456
789
"123"2","456","789"
123"2
456
789
"123",2","456","789"
123",2
456
789
"123","2","456","789"
123
2
456
789
答案 0 :(得分:2)
如果还考虑了非正则表达式方法,我建议删除初始和尾随引号(例如.Substring(1, s.Length - 2)
或.Trim('"')
),然后用{{1}分割字符串}:
使用
","
请参阅C# demo:
var elements = line.Substring(1, s.Length - 2).Split(new[] {"\",\""}, StringSplitOptions.None))
输出:
var s = "\"123\",\"456\",\"789\"";
Console.WriteLine(String.Join("|", s.Substring(1, s.Length - 2).Split(new[] {"\",\""}, StringSplitOptions.None)));
s = "\"123\"\",\"456\",\"789\"";
Console.WriteLine(String.Join("|", s.Substring(1, s.Length - 2).Split(new[] {"\",\""}, StringSplitOptions.None)));
s = "\"123\"2\",\"456\",\"789\"";
Console.WriteLine(String.Join("|", s.Substring(1, s.Length - 2).Split(new[] {"\",\""}, StringSplitOptions.None)));
s = "\"123\",2\",\"456\",\"789\"";
Console.WriteLine(String.Join("|", s.Substring(1, s.Length - 2).Split(new[] {"\",\""}, StringSplitOptions.None)));
s = "\"123\",\"2\",\"456\",\"789\"";
Console.WriteLine(String.Join("|", s.Substring(1, s.Length - 2).Split(new[] {"\",\""}, StringSplitOptions.None)));
答案 1 :(得分:0)
你可以尝试这样的正则表达式:
(?<=^"|,").*?(?=","|"$)
解释
(?<=^"|,") # positive lookbehind: one quote with comma before or at the start
.*? # match everything returning at first match
(?=","|"$) # positive lookahead: one quote with comma and quote after or at the end
希望它有所帮助。