Is str ~ regex the root of all evil, or the leaf of all good?

bearophile bearophileHUGS at lycos.com
Thu Feb 19 08:32:44 PST 2009


Andrei Alexandrescu:

>Excellent idea. Let's see:<

Thank you for all your work and the will to answer the posts here.
Some usable API is slowly shaping up :-)


> uint counter;
> string replacer(string) { return format("REPL%02d", counter++); }
> auto s1 = ".......TAG............TAG................TAG..........TAG.....";
> auto result = ".......REPL01............REPL02................REPL03..........REPL04...";
> r = replace!(replacer)(s1, "TAG");
> assert(r == result);

It looks good enough.

With a static variable it may become:

string replacer(string) {
    static int counter;
    return format("REPL%02d", counter++);
}


With small struct/class it may become:

struct Replacer {
    int counter;
    string opCall(string s) {
        this.counter++;
        return format("REPL%02d", counter);
    }
}

-------------------

> auto data = ">hello1 how are5 you?<";
> auto iter = match(data, regex(r".*?(hello\d).*?(are\d).*"));
> foreach (i; 0 .. iter.engine.captures)
>      writeln(iter.capture[i]);

I don't understand that.

What's the purpose of ".engine"?

"captures" may be better named "ngroups" or "ncaptures", or you may just use the .len/.length attribute in some way.

foreach (i, group; iter.groups)
    writeln(i " ", group);

"group" may be a struct that defines toString and can be cast to string, and also keeps the starting position of the group into the original string.

Bye,
bearophile



More information about the Digitalmars-d mailing list