【问题标题】:Regular expression with delimiters带分隔符的正则表达式
【发布时间】:2014-06-06 16:55:19
【问题描述】:

我想在 .NET 中使用正则表达式解析一些字符串,格式为分隔符为' 值,分隔符为& 值:

'A$04'&'A&&&'&'585262&YY'&'05555'

我发现的问题是分隔符& 也可以出现在每个值中。

你能告诉我如何在不使用循环的情况下做到这一点吗?我尝试了一些正则表达式,但没有成功。

【问题讨论】:

  • 发布您迄今为止尝试过的正则表达式...
  • 如果不需要检查数据结构,只能提取引号之间的内容。
  • 您可以分解/拆分'&'的字符串
  • 为什么你必须使用正则表达式? .NET 有一个解析器。文本字段解析器msdn.microsoft.com/en-us/library/…

标签: .net regex


【解决方案1】:

试试

'[^']+'(&'[^']+')*

除非您可以在字段中使用撇号,否则这应该有效。请注意,我假设您的字段不能为空 - 将 + 替换为 * 以处理这种情况。

【讨论】:

    【解决方案2】:
    string[] splitArray = null;
    try {
        splitArray = Regex.Split(subjectString, "'(.*?)'");
    } catch (ArgumentException ex) {
        // Syntax error in the regular expression
    }
    
    
    Match the character “'” literally «'»
    Match the regular expression below and capture its match into backreference number 1 «(.*?)»
       Match any single character that is not a line break character «.*?»
          Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
    Match the character “'” literally «'»
    

    【讨论】:

      【解决方案3】:

      另一种拆分方式:

      string[] values = Regex.Split("'A$04'&'A&&&'&'585262&YY'&'05555'", "(?<=')&(?=')");
      

      我们按&amp; 拆分,前面是',后面是'

      (?<=')&(?=')
      

      Debuggex Demo

      【讨论】:

        【解决方案4】:

        试试这个..

                var r = new Regex("'[A-Z0-9&$]*'",RegexOptions.IgnoreCase);
                var matches = r.Matches("'A$04'&'A&&&'&'585262&YY'&'05555'");
                foreach (var match in matches)
                {
                    var finalValue = match.ToString().Replace("'","");
                }
        

        【讨论】:

          猜你喜欢
          • 2021-11-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-27
          相关资源
          最近更新 更多