kw1jybo
kw1jybo

Reputation: 152

Get substring between first occurance of "A" and last occurance of "B"

I have a string which has two tokens that bound a substring that I want to extract, but the substring may contain the tokens themselves, so I want between the 1st occurrence of token A and the last occurrence of token B. I also need to search for the tokens in a case-insensitive search.

Tried to wrap my head around using regex to get this, but can't seem to figure it out. Not sure the best approach here. String.split won't work.

I can't modify the casing of the data between the tokens in the string.

Upvotes: 0

Views: 285

Answers (2)

flyte
flyte

Reputation: 1322

Try this, (I've made it into an extension method)

public static string Between(this string value, string a, string b)
{
    int posA = value.IndexOf(a);
    int posB = value.LastIndexOf(b);
    if (posA == -1) || (posB == -1)
    {
        return "";
    }

    int adjustedPosA = posA + a.Length;
    return (adjustedPosA >= posB) ? "" : value.Substring(adjustedPosA, posB - adjustedPosA);        
}

Usage would be:

var myString = "hereIsAToken_andThisIsWhatIwant_andSomeOtherToken";
var whatINeed = myString.Between("hereIsAToken_", "_andSomeOtherToken");

Upvotes: 6

Aaron
Aaron

Reputation: 1727

An easy way to approach this problem is the use of the indexOf function provided by the string class. IndexOf returns the first occurence, lastIndexOf as the name suggests, the last one.

string data;
string token1;
string token2;

int start = data.IndexOf(token1)+token1.Length;
int end = data.LastIndexOf(token2);

string result = data.Substring(start, end-start);

From my personal point of view, regex might be a bit overkill here, just try my example :)

Upvotes: 0

Related Questions