示例#1
0
        // delimitiers: ' " ( [ { ) ] } space
        // two continuous splitter can form a word boundary without presence of space
        // result of Bracketed or Quoted may not balanced or matched
        public static IEnumerable <(BalancedTermType termType, StringView termStr)> EachTerm(this StringView str)
        {
            int n = str.Length;
            int p, i;

            i = p = str.NextNonSpace(0);
            while (i != n)
            {
                char c = str[i];
                if (c == ' ')
                {
                    yield return(BalancedTermType.Spaced, str.GetSubView(p, i));

                    i = p = str.NextNonSpace(i);
                }
                else if (c.IsOpeningBracket())
                {
                    if (p != i)
                    {
                        yield return(BalancedTermType.Spaced, str.GetSubView(p, i));

                        p = i;
                    }
                    if ((i = str.BalanceBracket(i)) == str.Length)
                    {
                        throw new Exception("bracket are not balanced");
                    }
                    yield return(BalancedTermType.Bracketed, str.GetSubView(p, i + 1));

                    i = p = str.NextNonSpace(i + 1);
                }
                else if (c.IsQuote())
                {
                    if (p != i)
                    {
                        yield return(BalancedTermType.Spaced, str.GetSubView(p, i));

                        p = i;
                    }
                    if ((i = str.BalanceQuote(i)) == str.Length)
                    {
                        throw new Exception("quote are not balanced");
                    }

                    yield return(BalancedTermType.Quoted, str.GetSubView(p, i + 1));

                    i = p = str.NextNonSpace(i + 1);
                }
                else
                {
                    ++i;
                }
            }
            if (i != p)
            {
                yield return(BalancedTermType.Spaced, str.GetSubView(p, i));
            }
        }