1

Using the monadic parser Sprache, looking to match numeric characters (0..9), excluding non-numeric characters, but leading or trailing whitespace is ok.

I thought this should work:

public static readonly Parser<string>
    Number = Parse.Numeric.Except(Parse.Letter).AtLeastOnce().Text().Token();

or this:

public static readonly Parser<int>
    Number = Parse.Number.Select(int.Parse).Token();

Both work for all cases I could think of, except trailing text:

[Test]
public void Number_ParseNumberWithTrailingLetter_WasUnsuccessfull()
{
    var input = new Input("123bogus");
    IResult<string> result = Lexicon.Number(input);
    Assert.IsFalse(result.WasSuccessful);
}

Any clues?

si618
  • 16,580
  • 12
  • 67
  • 84
  • Did you `123a456` to return `123456`? Or `123`? – Geoff Apr 05 '13 at 20:27
  • Neither, it shouldn't parse. I'm after only numbers between whitespace. Updated question with a simpler expression which exhibits the same problem. – si618 Apr 07 '13 at 23:58
  • Is number/whitespace/number ok? I.e. should `"123 456"` parse as two discrete numbers? Or fail? – Geoff Apr 08 '13 at 03:41

1 Answers1

2

If the goal is to accept a single number only, then to eliminate the trailing text use a .End() clause, which asserts that the end of the string is reached:

public static readonly Parser<int> MatchInt =
      Parse.Number.Select(int.Parse).Token().End();

If instead you want to accept subsequent numbers in the input stream (separated by spaces), you could use a .Then() clause to give you all of them. Something like:

public static readonly Parser<int> MatchInt = Parse.Number.Select(int.Parse).Token();
public static readonly Parser<IEnumerable<int>> MatchIntList = 
      from int1 in MatchInt
      from intRest in Parse.WhiteSpace.AtLeastOnce().Then(_ => MatchInt).Many().End()
      select new List<int>() { int1 }.Concat(intRest);

Not tested - but hopefully enough to go in the right direction.

Geoff
  • 8,551
  • 1
  • 43
  • 50
  • Thanks Geoff! Only want a single number parsed, so the former solution works as expected. – si618 Apr 08 '13 at 07:02