Working with Parser Combinators: Listing 2.

Converting input into a PhoneNumber object.

public static Parser<string> fourNumberParser =
  Parse.Numeric.Then(first =>
    Parse.Numeric.Then(second =>
      Parse.Numeric.Then(third =>
        Parse.Numeric.Then(fourth =>
          Parse.Return("" + first.ToString() +
            second.ToString() + third.ToString() +
              fourth.ToString())))));
public static Parser<string> areaCodeParser =
  (from number in threeNumberParser
  select number).
  XOr(
  from lparens in Parse.Char('(')
  from number in threeNumberParser
  from rparens in Parse.Char(')')
  select number);
public static Parser<PhoneNumber> phoneParser =
  (from areaCode in areaCodeParser
  from _1 in Parse.WhiteSpace.Many().Text()
  from prefix in threeNumberParser
  from _2 in (Parse.WhiteSpace.Many().Text()).
  Or(Parse.Char('-').Many())
  from line in fourNumberParser
  select new PhoneNumber() { AreaCode=areaCode, Prefix=prefix, Line=line});

About the Author

Ted Neward is a programming language, virtual machine, and enterprise-scale architect. He has written a dozen books and hundreds of articles on .NET, Java, enterprise systems, mobile development, and programming languages. He resides in the Pacific Northwest, and can be found on the Internet at www.tedneward.com, www.itrellis.com, @tedneward on Twitter, and blogs at blogs.tedneward.com.

comments powered by Disqus

Featured

Subscribe on YouTube