检测字符串是否与格式说明符字符串匹配

时间:2015-02-26 05:45:26

标签: javascript regex string string-formatting

我正在尝试反向格式化字符串的过程,即将现有字符串与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];

为每个格式字符串构建正则表达式似乎是我能想到的最好的主意,但我不知道如何去做。我还想使用格式字符串提取字符串的值。

2 个答案:

答案 0 :(得分:3)

修改格式字符串以成为正则表达式:

  • %i替换为(-?[\d]+)
  • %s替换为(.*)
  • 添加开始和结束标记

结果如下:

var formats = [ 
    "^I have the number (-?[\d]+) and the word (.*)$", 
    "^(-?[\d]+) of your (.*) are belong to us$" 
];

在你的函数中,你遍历格式字符串,直到其中一个匹配。

答案 1 :(得分:2)

我在想和洛伦兹一样,因为它确实是唯一的选择。这是一个应该为你做的脚本。

您也可以使用它来转换您的数组。我甚至添加了逃避百分比符号的能力(如果只有js'正则表达式支持的外观,那将是一个更容易的任务)。

var strings = [
     "I have the number 5 and the word dog",
     "15 of your cows are belong to us",
     "1 of these strings should fail, because strings is matched against a %i."
];

var formats = [
    "I have the number %i and the word %s",
    "%i of your %s are belong to us",
    "1 of these strings should fail, because %i is matched against a \\%i."
];

var formex = [];
for (i=0; i<formats.length; i++) {
    formex[i] =  "^" + formats[i].replace(/([^\w\s\\%])/g,"\\$1").replace(/(^|[^\\])%i/gi,"$1\(\\d+\)").replace(/(^|[^\\])%s/gi,"$1\([a-z]+\)").replace(/\\%/g,"%") + "$";
}

console.log(formex);

for (i=0; i<formats.length; i++) {
    console.log("Testing: <" + strings[i] + "> against <" + formex[i] + ">.");
    console.log(strings[i].match(formex[i]));
}

Demo Fiddle