【问题标题】:Get the nth string of text between 2 separator characters获取 2 个分隔符之间的第 n 个文本字符串
【发布时间】:2011-09-21 16:30:43
【问题描述】:

我有一长串由字符(管道字符)分隔的文本。我需要获取第三和第四管道之间的文本。不知道该怎么做...

对正则表达式或非正则表达式开放,以最有效的为准。如果不存在可以传入的扩展方法,则特别开放:

  • 分隔符
  • 索引

【问题讨论】:

  • 难道你不能只用前一个管道的起始索引 indexOf 直到你到达第 3 个然后子串到第 4 个管道的索引(从第 3 个管道的索引开始)?或者只是在管道上使用字符串拆分:P
  • 我认为这个 indexOf 建议将是迄今为止最快的,因为它不会创建您不需要的一堆单独的字符串(和一个数组!)。这里的所有其他解决方案都会创建大量不需要的对象。

标签: c# regex parsing csv


【解决方案1】:

如果

string textBetween3rdAnd4thPipe = "zero|one|two|three|four".Split('|')[3];

没有做到你的意思,你需要解释的更详细。

【讨论】:

  • 我会选择这个答案而不是正则表达式。
【解决方案2】:

此正则表达式会将您想要的第三个和第四个| 之间的文本存储在$1

/(?:([^|]*)|){4}/


Regex r = new Regex(@"(?:([^|]*)|){4}");
r.match(string);
Match m = r.Match(text);
trace(m.Groups[1].captures);

【讨论】:

    【解决方案3】:

    试试这个

    public String GetSubString(this String originalStirng, StringString delimiter,Int32 Index)
    {
       String output = originalStirng.Split(delimiter);
       try
       {
          return output[Index];
       }
       catch(OutOfIndexException ex)
       {
          return String.Empty;
       }
    }
    

    【讨论】:

      【解决方案4】:

      你可以的

           string text = str.Split('|')[3];
      

      str 是你的长字符串。

      【讨论】:

        【解决方案5】:

        这是我的解决方案,我希望它比其他解决方案更有效,因为它不会创建一堆不需要的字符串和数组。

        /// <summary>
        /// Get the Nth field of a string, where fields are delimited by some substring.
        /// </summary>
        /// <param name="str">string to search in</param>
        /// <param name="index">0-based index of field to get</param>
        /// <param name="separator">separator substring</param>
        /// <returns>Nth field, or null if out of bounds</returns>
        public static string NthField(this string str, int index, string separator=" ") {
            int count = 0;
            int startPos = 0;
            while (startPos < str.Length) {
                int endPos = str.IndexOf(separator, startPos);
                if (endPos < 0) endPos = str.Length;
                if (count == index) return str.Substring(startPos, endPos-startPos);
                count++;
                startPos = endPos + separator.Length;
            }
            return null;
        }   
        

        【讨论】:

        • 这个实现的唯一一点不寻常的行为是,如果没有找到分隔符,则返回整个搜索字符串,即“abc”和“|abc|” (如果按照操作使用管道)都将返回“abc”。
        • 对于什么索引? NthField("abc", 0, "|") 当然返回 "abc",但是 NthField("|abc|", 0, "") 应该返回空字符串,因为它以分隔符开头。至于字段 1,NthField("abc", 1, "|"),它返回 null(而对于 "|abc|",它返回 "abc")。我想,一切都应该如此。还是我错过了什么?
        最近更新 更多