Extract

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 

Description

Extract a string from an other string between 2 char

Details

  • Author: tmcuh1982
  • Submitted on: 7/12/2016 3:46:22 PM
  • Language: C#
  • Type: string
  • Views: 789

Double click on the code to select all.

 

;