Decoding Pattern to a Tuple

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 19 11:04:02 PST 2016


On 02/19/2016 10:10 AM, Nordlöw wrote:
> Have anybody put together a generalised form of findSplit that can split
> and decode using a compile time parameters somewhat like
>
> "(1)-(2.0)".decode!("(", int, ")", char, "(", double, ")")
>
> evaluates to
>
> to a
>
> tuple!(int, char, double)
>
> with value
>
> tuple(1, '-', 2.0)

The following toy program works with that particular case but can be 
templatized:

import std.stdio;
import std.string;
import std.regex;
import std.typecons;
import std.conv;

auto decode(string s) {
     // Warning: Treats "012" as int (value 12), not octal (value 10).
     enum intClass = `[0-9]+`;

     enum charClass = `.`;

     // Found on the internet:
     enum floatClass = `[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?`;

     enum expr = format(`[(](%s)[)](%s)[(](%s)[)]`,
                        intClass, charClass, floatClass);
     enum r = ctRegex!expr;

     auto matched = s.match(r);

     if (matched) {
         foreach (e; matched) {
             // We are ignoring potential other matches on the same line and
             // returning just the first match. (Of course, no loop is 
needed.)
             return tuple(e[1].to!int, e[2].to!char, e[3].to!double);
         }
     }

     return Tuple!(int, char, double)();
}

void main() {
     auto t = decode("(1)-(2.5)");
     writeln(t);
}

Ali



More information about the Digitalmars-d-learn mailing list