Find text in string with C#
How can I find given text within a string? After that, I'd like to create a new string between that and something else. For instance, if the string was:
This is an example string and my data is here
And I want to create a string with whatever is between "my " and " is" how could I do that? This is pretty pseudo, but hopefully it makes sense.
Use this method:
public static string getBetween(string strSource, string strStart, string strEnd)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
int Start, End;
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
return "";
}
How to use it:
string source = "This is an example string and my data is here";
string data = getBetween(source, "my", "is");
This is the simplest way:
if(str.Contains("hello"))
You could use Regex:
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);
Here's my function using Oscar Jara's function as a model.
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;
}
This version does at most two searches of the text. It avoids an exception thrown by Oscar's version when searching for an end string that only occurs before the start string, i.e., getBetween(text, "my", "and");
.
Usage is the same:
string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");