使用给定格式从字符串中提取数据

时间:2017-04-11 08:53:54

标签: javascript

作为最近转移到JS的python程序员,我使用了一个名为的库 '解析'https://pypi.python.org/pypi/parse/1.8.0。 您为字符串提供了一个模板,实际的字符串将返回您想要的数据。例如:

parse("It's {}, I love it!", "It's spam, I love it!")

会返回spam

我一直在寻找这个问题的JS解决方案,除此之外我找不到任何东西: How can I extract data from a string using another string as a template?

我试过这个,但效果不好。 提前谢谢GoldPython

2 个答案:

答案 0 :(得分:0)

您可以使用RegExp实现此目的。

首先,您需要转义在RegExp中具有特殊含义的字符:

var toMatch = "I don't understand it, but: It's spam, I love it! I really really love it!";
var pattern = "It's {}, I love {}!";

function pythonParse(pattern, toMatch, bShortest) {
   pattern = pattern.replace(/\\/g,"\\\\");
   pattern = pattern.replace(/\$/g, "\\$");
   pattern = pattern.replace(/\^/g, "\\^");
   pattern = pattern.replace(/\(/g, "\\(");
   pattern = pattern.replace(/\)/g, "\\)");
   pattern = pattern.replace(/\[/g, "\\[");
   pattern = pattern.replace(/\]/g, "\\]");
   pattern = pattern.replace(/\%/g, "\\%");
   pattern = pattern.replace(/\?/g, "\\?");
   pattern = pattern.replace(/\:/g, "\\:");
   pattern = pattern.replace(/\//g, "\\/");
   pattern = pattern.replace(/\*/g, "\\*");
   pattern = pattern.replace(/\./g, "\\.");
   pattern = pattern.replace(/\+/g, "\\+");
   pattern = pattern.replace(/\|/g, "\\|");

   var lazy = "";
   if(bShortest)
     lazy = "?";

   // Replace the parse pattern {} with (.*) regex pattern
   pattern = pattern.replace(/\{\}/g, "(.*" + lazy + ")");

   // Then you can use this pattern to retrieve the result
   var matches = toMatch.match(new RegExp(pattern));
   // Count results
   if(!matches)
     return "";
   if(matches.length > 2) {
     matches.shift();
     return matches;
   }
   else
     return matches[1];
}  

var result = pythonParse(pattern, toMatch, true);
console.log(result);

请在此处查看工作示例:http://jsbin.com/vuluca/edit?js,console

EDITED允许使用可选的bShortest布尔参数进行延迟比较。

答案 1 :(得分:0)

已经找到了正则表达式的解决方案,无论如何,谢谢:) http://regexr.com/3fnm2