我可是森森呢 2023-08-22 22:31 采纳率: 96.3%
浏览 3
已结题

如何按指定条件分割字符串

我有个长字符串:data1 = '数据1' and data2 != '数 and 据' and data3 like '数据2'
如何分割成:
data1 = '数据1'
data2 != '数 and 据'
data3 like '数据2'
直接split("and"),会导致data2那里''内数据也被拆分。
正则的话,感觉有点复杂,不会写了。如何用正则匹配非''内的and?或者还有别的解决方法吗

  • 写回答

1条回答 默认 最新

  • threenewbee 2023-08-22 22:50
    关注
    
    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);
            }
          }
       }
    }
    
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月30日
  • 已采纳回答 8月22日
  • 创建了问题 8月22日

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向