Reputation: 36070
There is a similar question in here. In that question X happens to be (
and Y happened to be )
. I am looking for something like
public string GetStringBetweenStrings(string Source, string leftString, string rightString)
{
// implementation
Return middlePart;
}
So that when I call that method as:
var test = GetStringBetweenStrings("Hello World this is a test","World","test");
// then test = " this is a ";
how can I build that function
Upvotes: 1
Views: 227
Reputation: 15618
In the same linked question, you have a more flexible answer that works for all strings, modified here:
public string GetStringBetweenStrings(string source, string leftString, string rightString)
{
int start = source.IndexOf(leftString); // assume != -1
int end = source.IndexOf(rightString); // assume != -1 and >= start
if (start == -1 || end == -1 || end < start) return String.Empty;
return source.Substring(start + leftString.Length, end - start - rightString.Length - 1)
}
This assumes that both strings are contained in the source string. What behaviour do you want if either one isn't? Or if start is after end?
Obligatory regex version as per @Jack but updated into function:
public string GetStringBetweenStrings(string source, string leftString, string rightString)
{
return Regex.Match(source, String.Format(@"(?<={0})(.*)(?={1})",
Regex.Escape(leftString),
Regex.Escape(rightString)))
.Captures[0].Value;
}
Upvotes: 2
Reputation: 19231
IndexOf
is the most straight forward. Make sure you offset the start to past the first string. I also added some (untested) code to handle if left/right could overlap.
public string GetStringBetweenStrings(string Source, string leftString, string rightString)
{
var left = Source.IndexOf(leftString);
var right = Source.IndexOf(rightString);
while (right > -1 && left + leftString.Length >= right)
{
right = Source.IndexOf(rightString, right + 1);
}
if (left > -1 || right > -1 || left < right)
return null;
var start = left + leftString.Length;
var end = right;
return Source.Substring(start, end - start);
}
Upvotes: 0
Reputation: 5768
(?<=World).*(?=test)
Here's a regex solution. Replace World
and test
with your string variables when building the regex pattern.
Upvotes: 1
Reputation: 1223
Use the IndexOf function to locate the two strings. Then use SubString to extract what you need.
Upvotes: 0