|
Oktatás * Programozás 2 * Szkriptnyelvek * Adator. prog. Teaching • Prog. for Data Sci. Félévek Linkek * kalendárium |
Nim2 /
Extract data from a formatted stringSee also:
|
|||||||||||||||||||||
scanf()
| |
|
from parse import parse def main(): s = "mul(11,8)" p = parse("mul({a},{b})", s) print(p["a"]) # "11" print(p["b"]) # "8" |
import std/strscans let s = "mul(11,8)" var a, b: int if s.scanf("mul($i,$i)", a, b): echo a # 11 ; as int echo b # 8 ; as int var v1, v2: string if s.scanf("mul($+,$+)", v1, v2): echo v1 # "11" ; as string echo v2 # "8" ; as string |
|
This is a 3rd-party library. You can install it with |
|
The most important constructions (see the docs for a full list):
$i
| Matches a decimal integer. Uses parseInt.
|
$f
| Matches a floating-point number. Uses parseFloat.
|
$c
| Matches a single ASCII character. |
$s
| Skips optional whitespace(s). Matches multiple whitespace characters. |
$$
| Matches a single dollar sign. |
$*
| Matches until the token following the $* was found. The match is allowed to be of 0 length.
|
$+
| Matches until the token following the $+ was found. The match must consist of at least one char.
|
scanTuple()This module has another useful macro called scanTuple(). It's quite similar to C's scanf().
Let's say that we want to read a line from the standard input that contains three integers:
2 3 5
In C, we'd do this:
In Nim:
It returns a tuple. The tuple starts with a bool which indicates if the scan was successful followed by the requested data. If you're 100% sure that the input is correct, you can swallow the bool value by using the dummy variable underscore ('_').

Blogjaim, hobbi projektjeim
* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák
[ edit ]