Get the nth string of text between 2 separator characters

天大地大妈咪最大 提交于 2019-12-25 03:59:16

问题


I have a long string of text delimited by a character (pipe character). I need to get the 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

回答1:


If

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

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




回答2:


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



回答3:


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



回答4:


You could do

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

where str is your long string.




回答5:


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


来源:https://stackoverflow.com/questions/7503310/get-the-nth-string-of-text-between-2-separator-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!