Reputation: 11
public static string Between(this string value, string a, string b)
{
int posA = value.IndexOf(a);
int posB = value.LastIndexOf(b);
if (posA == -1)
{
return "";
}
if (posB == -1)
{
return "";
}
int adjustedPosA = posA + a.Length;
if (adjustedPosA >= posB)
{
return "";
}
return value.Substring(adjustedPosA, posB - adjustedPosA);
}
//Button1 Click
MessageBox.Show(Between("Abcdefgh- 50- 25------------ 37,50-#", "- ", "-#"));
The result is: 50- 25------------ 37,50
. But I want to select last '- '. So the result must be 37,50
.
Can anyone help me?
Upvotes: 0
Views: 202
Reputation: 2339
I'd use Regex.
public static string Between(this string value, string a, string b)
{
return Regex.Match(value, string.Format("((?:(?!{0}).)*){1}", Regex.Escape(a), Regex.Escape(b))).Groups[1].Value;
}
The regex is looking for the last occurrence of a before b and selects the characters between them.
Adapted from: https://stackoverflow.com/a/18264730/134330
Upvotes: 3