0
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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Maybe use `.LastIndexOf()` instead of `.IndexOf()`? When you step through this in a debugger, at what point does it differ from what you expect? Are the `posA` and `posB` values what you expect them to be? You're going to have to do at least *some* debugging. – David May 02 '14 at 14:59
  • 1
    you're looking for the first "- ", which is at "Abcdefgh- ". You need to change what you're looking for, because the code is working as it should. You need to better define what the logic should be across all of your cases. In this particular case, it looks like you may want `int posA = value.LastIndexOf(a);`, but I don't know if that fits all of your scenarios. – ps2goat May 02 '14 at 14:59

1 Answers1

3

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

Community
  • 1
  • 1
Josh
  • 2,259
  • 4
  • 22
  • 25