[c#] Get String In between strings

Status
Not open for further replies.

jayfella

Active Member
1,600
2009
565
700
This static string will obtain a string in between 2 strings.

For example. I have the string:

Code:
<a href="myfile.php">foo-bar</a>
If i wanted to get the name of the link (foo-bar):

Code:
result = GetStringInbetween("\">", "</a>", sourceFile, false, false);
string myString = result[0];
the last two boolean values allow you to choose whether to include your beginning string and ending string with the result.

Code:
string[] result;

public static string[] GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
        {
            string[] result = { "", "" };
            int iIndexOfBegin = strSource.IndexOf(strBegin);
            if (iIndexOfBegin != -1)
            {
                if (includeBegin)
                { iIndexOfBegin -= strBegin.Length; }
                strSource = strSource.Substring(iIndexOfBegin
                    + strBegin.Length);
                int iEnd = strSource.IndexOf(strEnd);

                if (iEnd != -1)
                {
                    if (includeEnd)
                    { iEnd += strEnd.Length; }
                    result[0] = strSource.Substring(0, iEnd);
                    if (iEnd + strEnd.Length < strSource.Length)
                    { result[1] = strSource.Substring(iEnd + strEnd.Length); }
                }
            }
            else
            { result[1] = strSource; }
            return result;
        }
 
3 comments
Would you be able to do a regex or a XML version of this

What if we had <a href="myfile.php"><span class="foo">bar</span></a>

would return bar</span> right
 
yes thats exactly what it would return in the example you gave yes.

The XML parser i posted previously does what you need for XML. It gets/sets node values.
 
Would you be able to do a regex or a XML version of this

Never parse markup with regex's, ever. Jay's method is how it should be done. To fully parse XML you'd do that sort of magic with the help of a FSM.

Edit:
My bad :(. Actually you're right since this isn't meant to parse. But still if it can be done with string functions it should because they are a hell of a lot faster.
 
Status
Not open for further replies.
Back
Top