Returns the part of the string starting at the first opening bracket and ending with the matching closing bracket, or null when the original text does not contain brackets or is unbalanced. - CSharp System

CSharp examples for System:String Contain

Description

Returns the part of the string starting at the first opening bracket and ending with the matching closing bracket, or null when the original text does not contain brackets or is unbalanced.

Demo Code


using System;/*w  ww .  ja  v a2 s .com*/

public class Main{
        /// <summary>
        /// Returns the part of the string starting at the first opening bracket and ending with the matching closing bracket, 
        /// or null when the original text does not contain brackets or is unbalanced.
        /// </summary>
        public static string FirstMatchingBrackets(this string originalText)
        {
            if (String.IsNullOrEmpty(originalText))
            {
                return null;
            }

            int start = 0;
            int end = 0;
            int level = 0;
            bool betweenQuotes = false;
            char quoteChar = '"';
            for (var i = 0; i < originalText.Length; i++)
            {
                char current = originalText[i];

                if (!betweenQuotes)
                {
                    if (current == '\'')
                    {
                        quoteChar = '\'';
                        betweenQuotes = true;
                    }
                    else if (current == '"')
                    {
                        quoteChar = '"';
                        betweenQuotes = true;
                    }
                    else
                    {
                        if (current == '(')
                        {
                            if (level == 0)
                            {
                                start = i;
                            }
                            level++;
                        }
                        else if (current == ')')
                        {
                            level--;
                            if (level == 0)
                            {
                                end = i;
                                // matching bracket found, we can stop now.
                                break;
                            }
                        }
                    }
                }
                else
                {
                    // between quotes
                    if (current == quoteChar)
                    {
                        betweenQuotes = false;
                    }
                }
            }

            if (end > 0)
            {
                return originalText.Substring(start, end-start+1);
            }

            return null;
        }
}

Related Tutorials