wiki example

53 views
Skip to first unread message

Pavel

unread,
Jul 11, 2012, 11:30:02 AM7/11/12
to sprache...@googlegroups.com
Hi everyone,

For some reason i'm struggling with this: I need to to parse the string (without the quotes)

"one, two|three {{four|five}}six [[seven [[eight]] ]]"
into a list of Items, so that the items are 
Word: one
Word: two
Word: three
Reference: 
  Word: four
  Word: five
Word: six

This is what I have, and i'm failing on the {{four|five}} part. I haven't gotten to the [[ ]] :

    public class Reference : Item {
        private IEnumerable<Item> refContent;

        public Reference(IEnumerable<Item> refContent)
        {
            this.refContent = refContent;
        }

        public override string ToString()
        {
            return @"{{" +
                refContent.Aggregate("", (s, c) => s + c)
                 + @"}}";
        }
    }

    public class Item {}

    public class Word : Item
    {
        public Word(string word)
        {
            this.Content = word;
        }
        public string Content { get; set; }
        public override string ToString()
        {
            return Content;
        }
    }

static readonly Parser<string> WordSeparator = 
            from separator in Parse.AnyChar
                .Except(Parse.LetterOrDigit)
                .Except(Parse.String("{{"))
                .Many().Text().Token() 
            select separator;

        static readonly Parser<Item> Word =
            from first in Parse.Letter.Once()
            from rest in Parse.LetterOrDigit.Many()//XOr(Parse.Char('-')).XOr(Parse.Char('_')).Many()
            from trailing in WordSeparator
            //from whitespaceOrEnd in Parse.WhiteSpace.Many()
            select new Word(new string(first.Concat(rest).ToArray()));

         static readonly Parser<Reference> Reference =
            from opening in Parse.String("{{")
            from refContent in Parse.Ref(() => Item.Select(n => new Reference(n))
            from closing in Parse.String("}}")
            select refContent;

        public static readonly Parser<IEnumerable<Item>> Item =
            from word in Reference.Or(Word).Many().Token()
            //from whitespaceOrEnd in Parse.WhiteSpace.Many()
            select word;

If anyone has any ideas, please let me know. I've tried looking at the examples, and i think i'm close, but just missing something. 

Thanks in advance!
-Pavel
Reply all
Reply to author
Forward
0 new messages