Haxe 中的字符串 substitution/String 格式化

String substitution/String formating in Haxe

一个最常用的功能是字符串 substitution/string 格式化。例如以下命令之一:

"Hi my name is %s and I'm %s years old" % ("Derp", 12)

"Hi my name is {0} and I'm {1} years old".format("Derp", 12)

将评估为

Hi my name is Derp and I'm 12 years old

在 python 中。有没有一种(预定义的)方法可以在 Haxe 中做类似的事情?

是的。

它在 Haxe 中被称为 String Interpolation

相当于:

var name = "Mark";
var age = 31;
var message = 'Hi my name is $name and Im $age years old';
trace(message);

然而,字符串插值是一个编译时特性,基本上将其转换为:
"Hi my name is " + name + " and I'm " + age + " years old"

如果您使用动态文本(例如翻译和内容)并想要您建议的格式,那么您可以使用这样的正则表达式:

using Main.StringUtil;

class Main {
    public static function main() {
        var message = "hi my name is {0} and I'm {1} years old".format(["mark", 31]);
        trace(message);
    }
}

class StringUtil {
    public static function format(value:String, values:Array<Any>) {
        var ereg:EReg = ~/(\{(\d{1,2})\})/g;
        while (ereg.match(value)) {
            value = ereg.matchedLeft() + values[Std.parseInt(ereg.matched(2))] + ereg.matchedRight();
        }
        return value;
    }
}

在线尝试:https://try.haxe.org/#381c8

The using at the top of the class allows to use a string as mixin "".format() (this is called static extension in Haxe).


更新: 没有正则表达式你可以这样做:

using StringTools;
using Main.StringUtil;

class Main {
    public static function main() {
        var message = "hi my name is {0} and I'm {1} years old".format(["mark", 31]);
        trace(message);
    }
}

class StringUtil {
    public static function format(value:String, values:Array<Any>) {
        for (i in 0...values.length) {
            value = value.replace('{$i}', values[i]);
        }
        return value;
    }
}

在线尝试:https://try.haxe.org/#8A17A