我正在尝试反向格式化字符串的过程,即将现有字符串与类似 printf 的字符串格式说明符字符串相匹配。
我有一个由多个字符串组成的数组,如下所示:
var strings = [
"I have the number 5 and the word dog",
"15 of your cows are belong to us"
];
我还有一个与这些字符串对应的格式字符串数组:
var formats = [
"I have the number %i and the word %s",
"%i of your %s are belong to us"
];
在我的特定用例中,我只需要匹配整数和单个单词字符串。
function getFormatString(string) {
//What I'm trying to accomplish
}
getFormatString(strings[0]); //returns formats[0];
getFormatString(strings[1]); //returns formats[1];
为每个格式字符串构建正则表达式似乎是我能想到的最好的主意,但我不确定如何去做。我还想使用格式字符串提取字符串的值。
最佳答案
修改格式字符串以成为正则表达式:
- 将
%i
替换为(-?[\d]+)
- 将
%s
替换为(.*)
- 添加开始和结束标记
这是结果:
var formats = [
"^I have the number (-?[\d]+) and the word (.*)$",
"^(-?[\d]+) of your (.*) are belong to us$"
];
在您的函数中,您循环遍历格式字符串,直到其中一个匹配。
关于javascript - 检测字符串是否与格式说明符字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28735316/