开发者

Get the nth string of text between 2 separator characters

开发者 https://www.devze.com 2023-04-06 06:19 出处:网络
I have a long string of text delimited by a character (pipe character). I need to get th开发者_运维问答e text between the 3rd and 4th pipes. Not sure how to go about this...

I have a long string of text delimited by a character (pipe character). I need to get th开发者_运维问答e text between the 3rd and 4th pipes. Not sure how to go about this...

Open to regex or non-regex, whichever is the most efficient. Especially open to extension method if none exist to be able to pass in:

  • seperatorChar
  • index


If

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

doesn't do what you mean, you need to explain in more detail.


This regex will store the text between the 3rd and 4th | you want in $1

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


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


Try This

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;
   }
}


You could do

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

where str is your long string.


Here's my solution, which I expect to be more efficient than the others because it's not creating a bunch of strings and an array that are not needed.

/// <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;
}   
0

精彩评论

暂无评论...
验证码 换一张
取 消