ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Extract

Extract a string from an other string between 2 char

Source

public static string Extract(this string value, string begin_text, string end_text, int occur=1)
{
    if (string.IsNullOrEmpty(value) == false)
    {
        // Search Begin
        int start = -1;
        // search with number of occurs
        for(int i=1; i<=occur;i++)
            start = value.IndexOf(begin_text, start+1);

        if (start < 0)
            return value;
        start += begin_text.Length;


        // Search End
        if(string.IsNullOrEmpty(end_text))
            return value.Substring(start);
        int end = value.IndexOf(end_text, start);
        if (end < 0)
            return value.Substring(start);

        end -= start;

        // End Final
        return value.Substring(start, end);
    }
    else
    {
        return value;
    }

}

Example

"my message {yes} {no}".Extract("{", "}");  // return yes
"my message {yes} {no}".Extract("{", "}",2);  // return no
"my message {yes} {no}".Extract("", "{");     // return my message

Author: tmcuh1982

Submitted on: 12 jul. 2016

Language: C#

Type: string

Views: 3820