如何在字符串中找到给定的文本?在那之后,我想在它和其他东西之间创建一个新的字符串.例如...
如果字符串是:
This is an example string and my data is here
我想创建一个字符串,其中包含"my"和"is"之间的任何内容,我该怎么做?对不起,这很伪,但希望它有意义.
Osc*_*car 148
使用此功能.
public static string getBetween(string strSource, string strStart, string strEnd)
{
    int Start, End;
    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
    {
        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        End = strSource.IndexOf(strEnd, Start);
        return strSource.Substring(Start, End - Start);
    }
    else
    {
        return "";
    }
}
如何使用它:
string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");
Kem*_*ran 61
这是最简单的方法:
if(str.Contains("hello"))
Mic*_*elZ 24
你可以使用正则表达式:
var regex = new Regex(".*my (.*) is.*");
if (regex.IsMatch("This is an example string and my data is here"))
{
    var myCapturedText = regex.Match("This is an example string and my data is here").Groups[1].Value;
    Console.WriteLine("This is my captured text: {0}", myCapturedText);
}
 string string1 = "This is an example string and my data is here";
 string toFind1 = "my";
 string toFind2 = "is";
 int start = string1.IndexOf(toFind1) + toFind1.Length;
 int end = string1.IndexOf(toFind2, start); //Start after the index of 'my' since 'is' appears twice
 string string2 = string1.Substring(start, end - start);
这是我使用 Oscar Jara 的函数作为模型的函数。
public static string getBetween(string strSource, string strStart, string strEnd) {
   const int kNotFound = -1;
   var startIdx = strSource.IndexOf(strStart);
   if (startIdx != kNotFound) {
      startIdx += strStart.Length;
      var endIdx = strSource.IndexOf(strEnd, startIdx);
      if (endIdx > startIdx) {
         return strSource.Substring(startIdx, endIdx - startIdx);
      }
   }
   return String.Empty;
}
此版本最多对文本进行两次搜索。它避免了 Oscar 版本在搜索仅出现在开始字符串之前的结束字符串时抛出的异常,即getBetween(text, "my", "and");。
用法是一样的:
string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");