blob: 90660fc8c38a1dbddb51730f36638ee3ac52df4d [file] [log] [blame] [view]
John McCutchan9f605592015-09-17 14:09:47 -07001This package exposes a `StringScanner` type that makes it easy to parse a string
2using a series of `Pattern`s. For example:
3
4```dart
5import 'dart:math';
6
7import 'package:string_scanner/string_scanner.dart';
8
9num parseNumber(String source) {
10 // Scan a number ("1", "1.5", "-3").
11 var scanner = new StringScanner(source);
12
13 // [Scanner.scan] tries to consume a [Pattern] and returns whether or not it
14 // succeeded. It will move the scan pointer past the end of the pattern.
15 var negative = scanner.scan("-");
16
17 // [Scanner.expect] consumes a [Pattern] and throws a [FormatError] if it
18 // fails. Like [Scanner.scan], it will move the scan pointer forward.
19 scanner.expect(new RegExp(r"\d+"));
20
21 // [Scanner.lastMatch] holds the [MatchData] for the most recent call to
22 // [Scanner.scan], [Scanner.expect], or [Scanner.matches].
23 var number = int.parse(scanner.lastMatch[0]);
24
25 if (scanner.scan(".")) {
26 scanner.expect(new RegExp(r"\d+"));
27 var decimal = scanner.lastMatch[0];
28 number += int.parse(decimal) / math.pow(10, decimal.length);
29 }
30
31 // [Scanner.expectDone] will throw a [FormatError] if there's any input that
32 // hasn't yet been consumed.
33 scanner.expectDone();
34
35 return (negative ? -1 : 1) * number;
36}
37```