|
| 1 | +// Copyright (c) 2019, 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 | +import 'dart:math' as math; |
| 6 | + |
| 7 | +import 'package:string_scanner/string_scanner.dart'; |
| 8 | + |
| 9 | +void main(List<String> args) { |
| 10 | + print(parseNumber(args.single)); |
| 11 | +} |
| 12 | + |
| 13 | +num parseNumber(String source) { |
| 14 | + // Scan a number ("1", "1.5", "-3"). |
| 15 | + var scanner = StringScanner(source); |
| 16 | + |
| 17 | + // [Scanner.scan] tries to consume a [Pattern] and returns whether or not it |
| 18 | + // succeeded. It will move the scan pointer past the end of the pattern. |
| 19 | + var negative = scanner.scan("-"); |
| 20 | + |
| 21 | + // [Scanner.expect] consumes a [Pattern] and throws a [FormatError] if it |
| 22 | + // fails. Like [Scanner.scan], it will move the scan pointer forward. |
| 23 | + scanner.expect(RegExp(r"\d+")); |
| 24 | + |
| 25 | + // [Scanner.lastMatch] holds the [MatchData] for the most recent call to |
| 26 | + // [Scanner.scan], [Scanner.expect], or [Scanner.matches]. |
| 27 | + var number = num.parse(scanner.lastMatch[0]); |
| 28 | + |
| 29 | + if (scanner.scan(".")) { |
| 30 | + scanner.expect(RegExp(r"\d+")); |
| 31 | + var decimal = scanner.lastMatch[0]; |
| 32 | + number += int.parse(decimal) / math.pow(10, decimal.length); |
| 33 | + } |
| 34 | + |
| 35 | + // [Scanner.expectDone] will throw a [FormatError] if there's any input that |
| 36 | + // hasn't yet been consumed. |
| 37 | + scanner.expectDone(); |
| 38 | + |
| 39 | + return (negative ? -1 : 1) * number; |
| 40 | +} |
0 commit comments