简体   繁体   中英

Parsing a list of values with option to empty list

I'm trying to parse an array of items, using Sprache library for C# I have a working code that goes like this.

public static Parser<string> Array =
    from open in OpenBrackets.Named("open bracket")
    from items in Literal.Or(Identifier).Or(Array).DelimitedBy(Comma).Optional()
    from close in CloseBrackets.Named("close bracket")
    select open + (items.IsDefined ? string.Join(", ", items.Get()) : " ") + close;

where "Literal" is a parser for numbers or strings, "Identifier" is a parser for a variable identifier and "Comma" is a parser for a comma token. But if I want the array to allow being empty "[ ]" I need to add the Optional() property and verify if "items" is defined:

select open + (items.IsDefined ? string.Join(", ", items.Get()) : " ") + close;

Is there a better cleaner way to do this for parsing a list of items separated by a separator char, that can be empty (list). That I can reuse with other lists of items.

Sample of input data structure:

[Literal/Identifier/Array] => Value;
[Value] [,Value]* => Array

[public/private] [identifier]; => Declaration;
[public/private] [identifier] [[=] [Value]] => Initialization;

可以使用GetOrElse方法完成一种更GetOrElse方法。

select open + string.Join(", ", items.GetOrElse(new string[0])) + close;

Try using Regex as in code below :

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {

        const string FILENAME = @"c:\temp\test.txt";
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(FILENAME);
            string pattern = @"\[(?'bracketData'[^\]]+)\](?'repeat'[*+])?";
            string line = "";
            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if (line.Length > 0)
                {
                    string suffix = line.Split(new string[] {"=>"}, StringSplitOptions.None).Select(x => x.Trim()).Last();

                    MatchCollection matches = Regex.Matches(line, pattern);

                    var brackets = matches.Cast<Match>().Select(x => new { bracket = x.Groups["bracketData"].Value, repeat = x.Groups["repeat"].Value }).ToArray();

                    Console.WriteLine("Brackets : '{0}'; Suffix : '{1}'", string.Join(",", brackets.Select(x => "(" + x.bracket + ")" + x.repeat )), suffix);
                }
            }
            Console.ReadLine();

        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM