I just wrote an article about various parsing methods in Nim, based on my Advent of Code solutions.
If you never used scanf macro or npeg library, take a look: https://narimiran.github.io/2021/01/11/nim-parsing.html
What would be really cool is something akin to a “reverse fmt” where you specify the variable names and types on the pattern sting itself. For example:
strscan(input, "({x:d},{y:d},{z:d})")
Or even:
strscan(input, "({x},{y},{z})")
Which would take the type from the variable type.
Does something like that exist?
I use ruby-like wrapper around nim's re, compared to the scanf code from the article
var min1, max1, min2, max2: int
var field: string
for line in input.split("\n"):
if line.scanf("$+: $i-$i or $i-$i", field, min1, max1, min2, max2):
echo [min1..max1, min2..max2]
With ruby-like wrapper it looks like:
for line in input.split("\n"):
let found = re".+: (\d+)-(\d+) or (\d+)-(\d+)".parse4(line)
if found.is_some:
let (min1, min2, min3, min4) = found.get
echo [min1..max1, min2..max2]
Yea that's where the scanTuple came from originally it did automatically declare the variables, but Araq prefered the tuple method, so it's what we get, it's equally as good.
let (success, field, min1, max1, min1, max1) = line.scanTuple("$+: $i-$i or $i-$i")
if success:
echo field, " is", [min1..max1, min2..max2]
Aww no honourable mention of the strscans.scanTuple in devel. :(
I tried to avoid "devel only" stuff. That's why I didn't choose the example where I use $c, which is also a new scanf feature available in devel.
But I like scanTuple and I'll probably use it in the future.