使用C#查找字符串中的文本

Wil*_*son 65 c# string find

如何在字符串中找到给定的文本?在那之后,我想在它和其他东西之间创建一个新的字符串.例如...

如果字符串是:

This is an example string and my data is here
Run Code Online (Sandbox Code Playgroud)

我想创建一个字符串,其中包含"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 "";
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用它:

string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");
Run Code Online (Sandbox Code Playgroud)

  • 不能告诉你你的短功能是多么有用 - 谢谢. (4认同)
  • 功能很棒!请将局部变量名称更改为小写字母开头。您还可以将 strSource.IndexOf(strStart, 0) 更改为 strSource.IndexOf(strStart) 。你不必声明`int start, end`,你可以只写`int start = strSource.IndexOf...` (3认同)

Kem*_*ran 61

这是最简单的方法:

if(str.Contains("hello"))
Run Code Online (Sandbox Code Playgroud)

  • 这根本不是问题的解决方案.为什么这个被投票? (21认同)
  • 因为这是我一直在寻找我的问题的解决方案(这与OP的问题不同).当我搜索我的问题时,谷歌让我到了这个页面. (20认同)
  • 是的,但答案是关于OP的问题,而不是一些随机的东西...... :) (2认同)
  • 同意。另外,我正在搜索与谷歌上原始帖子问题类似的内容,到达此页面,我对这个答案感到困惑,这不是我想要的。 (2认同)

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);
}
Run Code Online (Sandbox Code Playgroud)


Kev*_*lia 7

 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);
Run Code Online (Sandbox Code Playgroud)


Joh*_*Cee 5

这是我使用 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;
}
Run Code Online (Sandbox Code Playgroud)

此版本最多对文本进行两次搜索。它避免了 Oscar 版本在搜索仅出现在开始字符串之前的结束字符串时抛出的异常,即getBetween(text, "my", "and");

用法是一样的:

string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");
Run Code Online (Sandbox Code Playgroud)