using System.Collections.Generic;
|
using System.Text;
|
|
namespace AddInPlugin.Util
|
{
|
public class ExpressUtil
|
{
|
/// <summary>
|
/// 按逗号分割字符串,忽略引号内的逗号
|
/// </summary>
|
/// <param name="input">输入字符串</param>
|
/// <param name="trim">是否去除每项首尾空格</param>
|
/// <param name="removeEmpty">是否移除空项</param>
|
/// <returns>分割后的数组</returns>
|
public static string[] SplitIgnoringQuotes(string input, bool trim = false, bool removeEmpty = true, char escapeChar = '\\')
|
{
|
if (string.IsNullOrEmpty(input))
|
return new string[0];
|
|
List<string> result = new List<string>();
|
StringBuilder current = new StringBuilder();
|
bool inQuotes = false;
|
int parenDepth = 0; // 圆括号嵌套深度
|
int bracketDepth = 0; // 方括号嵌套深度
|
|
for (int i = 0; i < input.Length; i++)
|
{
|
char c = input[i];
|
|
// 处理转义引号:\" 表示引号字符本身,不是引号边界
|
if (c == escapeChar && i + 1 < input.Length && input[i + 1] == '"')
|
{
|
current.Append('"');
|
i++; // 跳过下一个字符(引号字符)
|
continue;
|
}
|
|
// 处理引号边界
|
if (c == '"')
|
{
|
inQuotes = !inQuotes;
|
current.Append(c);
|
continue;
|
}
|
|
// 如果在引号内,直接添加字符
|
if (inQuotes)
|
{
|
current.Append(c);
|
continue;
|
}
|
|
// 处理圆括号
|
if (c == '(')
|
{
|
parenDepth++;
|
current.Append(c);
|
continue;
|
}
|
else if (c == ')')
|
{
|
if (parenDepth > 0)
|
parenDepth--;
|
current.Append(c);
|
continue;
|
}
|
|
if (c == '[')
|
{
|
bracketDepth++;
|
current.Append(c);
|
continue;
|
}
|
else if (c == ']')
|
{
|
if (bracketDepth > 0)
|
bracketDepth--;
|
current.Append(c);
|
continue;
|
}
|
|
// 处理逗号分隔符(不在引号内,不在括号内,不在方括号内)
|
if (c == ',' && parenDepth == 0 && bracketDepth == 0)
|
{
|
AddItem(result, current, trim, removeEmpty);
|
current.Clear();
|
continue;
|
}
|
|
// 其他字符,直接添加
|
current.Append(c);
|
}
|
|
// 添加最后一项
|
AddItem(result, current, trim, removeEmpty);
|
|
return result.ToArray();
|
}
|
|
private static void AddItem(List<string> result, StringBuilder current, bool trim, bool removeEmpty)
|
{
|
string item = trim ? current.ToString().Trim() : current.ToString();
|
if (!removeEmpty || !string.IsNullOrEmpty(item))
|
result.Add(item);
|
}
|
}
|
}
|