我有个长字符串:data1 = '数据1' and data2 != '数 and 据' and data3 like '数据2'
如何分割成:
data1 = '数据1'
data2 != '数 and 据'
data3 like '数据2'
直接split("and"),会导致data2那里''内数据也被拆分。
正则的话,感觉有点复杂,不会写了。如何用正则匹配非''内的and?或者还有别的解决方法吗
using System;
using System.Collections.Generic;
namespace HelloWorldApplication
{
class HelloWorld
{
static string[] ParseLine(string line, string delimiter, char quote)
{
List<string> result = new List<string>();
bool inQuotes = false;
string currentField = "";
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
char nextChar = i < line.Length - 1 ? line[i + 1] : '\0';
if (c == quote)
{
// 处理引号内的字段
if (nextChar == quote)
{
// 双引号转义为单引号
currentField += quote;
i++;
}
else
{
// 引号的开始或结束
inQuotes = !inQuotes;
}
}
else if (line.Substring(i).StartsWith(delimiter) && !inQuotes)
{
// 分隔符分隔的字段
result.Add(currentField);
currentField = "";
i += delimiter.Length - 1;
}
else
{
// 添加字符到当前字段
currentField += c;
}
}
// 添加最后一个字段
result.Add(currentField);
return result.ToArray();
}
static void Main(string[] args)
{
string line = "data1 = '数据1' and data2 != '数 and 据' and data3 like '数据2";
string delimiter = " and ";
char quote = '\'';
string[] fields = ParseLine(line, delimiter, quote);
foreach (string field in fields)
{
Console.WriteLine(field);
}
}
}
}