replaceFromAA

Replaces space-separated tokens (that begin with a token character) in a string with values from a supplied associative array.

The AA values are of some type of function or delegate returning strings.

@safe
replaceFromAA
(
char tokenCharacter = '$'
Fn
)
(
const string line
,
const Fn[string] aa
)

Parameters

tokenCharacter

What character to use to denote tokens, defaults to '$' but may be any char.

line string

String to replace tokens in.

aa Fn[string]

Associative array of token keys and replacement callable values.

Return Value

Type: auto

A new string with occurrences of any passed tokens replaced, or the original string as-is if there were no changes made.

Examples

const @safe string delegate()[string] aa =
[
    "$foo"  : () => "bar",
    "$baz"  : () => "quux"
    "$now"  : () => Clock.currTime.toISOExtString(),
    "$rng"  : () => uniform(0, 100).to!string,
    "$hirr" : () => 10.to!string,
];

immutable line = "first $foo second $baz third $hirr end";
enum expected = "first bar second quux third 10 end";
immutable actual = line.replaceFromAA(aa);
assert((actual == expected), actual);
static auto echo(const string what) { return what; }

immutable hello = "hello";

@safe string delegate()[string] aa =
[
    "$foo" : () => hello,
    "$bar" : () => echo("I was one"),
    "$baz" : () => "BAZ",
];

enum line = "I thought what I'd $foo was, I'd pretend $bar of those deaf-$baz";
enum expected = "I thought what I'd hello was, I'd pretend I was one of those deaf-BAZ";
immutable actual = line.replaceFromAA(aa);
assert((actual == expected), actual);