OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library shelf.string_scanner; |
| 6 |
| 7 /// A class that scans through a string using [Pattern]s. |
| 8 class StringScanner { |
| 9 /// The string being scanned through. |
| 10 final String string; |
| 11 |
| 12 /// The current position of the scanner in the string, in characters. |
| 13 int get position => _position; |
| 14 set position(int position) { |
| 15 if (position < 0 || position > string.length) { |
| 16 throw new ArgumentError("Invalid position $position"); |
| 17 } |
| 18 |
| 19 _position = position; |
| 20 } |
| 21 int _position = 0; |
| 22 |
| 23 /// The data about the previous match made by the scanner. |
| 24 /// |
| 25 /// If the last match failed, this will be `null`. |
| 26 Match get lastMatch => _lastMatch; |
| 27 Match _lastMatch; |
| 28 |
| 29 /// The portion of the string that hasn't yet been scanned. |
| 30 String get rest => string.substring(position); |
| 31 |
| 32 /// Whether the scanner has completely consumed [string]. |
| 33 bool get isDone => position == string.length; |
| 34 |
| 35 /// Creates a new [StringScanner] that starts scanning from [position]. |
| 36 /// |
| 37 /// [position] defaults to 0, the beginning of the string. |
| 38 StringScanner(this.string, {int position}) { |
| 39 if (position != null) this.position = position; |
| 40 } |
| 41 |
| 42 /// If [pattern] matches at the current position of the string, scans forward |
| 43 /// until the end of the match. |
| 44 /// |
| 45 /// Returns whether or not [pattern] matched. |
| 46 bool scan(Pattern pattern) { |
| 47 var success = matches(pattern); |
| 48 if (success) _position = _lastMatch.end; |
| 49 return success; |
| 50 } |
| 51 |
| 52 /// If [pattern] matches at the current position of the string, scans forward |
| 53 /// until the end of the match. |
| 54 /// |
| 55 /// If [pattern] did not match, throws a [FormatException] with [message]. |
| 56 void expect(Pattern pattern, String message) { |
| 57 if (scan(pattern)) return; |
| 58 throw new FormatException(message); |
| 59 } |
| 60 |
| 61 /// Returns whether or not [pattern] matches at the current position of the |
| 62 /// string. |
| 63 /// |
| 64 /// This doesn't move the scan pointer forward. |
| 65 bool matches(Pattern pattern) { |
| 66 _lastMatch = pattern.matchAsPrefix(string, position); |
| 67 return _lastMatch != null; |
| 68 } |
| 69 } |
OLD | NEW |