我想生成匹配特定模式的字符串。例如,该函数将采用两个参数:
function parsePattern(pattern, string) {}
并且接受的模式可能是 '(hello|hi), %i, (how are you|nice to see you)' 并且如果第二个参数以这种方式设置为 'John'
parsePattern('(hello|hi), %i, (how are you|nice to see you)', 'John')
我希望输出具有所有可能的组合:
'hello, John, how are you'
'hello, John, nice to see you'
'hi, John, how are you'
'hi, John, nice to see you'
实现这一目标的最佳方法是什么?
您正在寻找与正则表达式通常用于相反的操作,因此对于更通用的正则表达式模式(如\w+
. 但是,如果您只是想为A|B
示例中的模式类型生成结果,这里有一些代码可以实现这一点。这利用了StackOverflow 自己的 formatUnicorn 函数以及这里给出的笛卡尔积函数。当然,您可以用自己的替换这些。
JSFiddle:https ://jsfiddle.net/aro108zc/
String.prototype.formatUnicorn = String.prototype.formatUnicorn ||
function () {
"use strict";
var str = this.toString();
if (arguments.length) {
var t = typeof arguments[0];
var key;
var args = ("string" === t || "number" === t) ?
Array.prototype.slice.call(arguments)
: arguments[0];
for (key in args) {
str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
}
}
return str;
};
function cartesianProduct(arr) {
return arr.reduce(function (a, b) {
return a.map(function (x) {
return b.map(function (y) {
return x.concat([y]);
})
}).reduce(function (a, b) { return a.concat(b) }, [])
}, [[]])
}
function parsePattern(pattern, str) {
var regex = /\(([^|()]+\|)*[^|()]+\)/g;
var results = [];
var matches = pattern.match(regex);
// replace input string match groups with format strings
matches.forEach(function (el, idx) {
pattern = pattern.replace(el, '{' + (idx + 1) + '}');
});
// split matches into parts
var matchesSplit = [];
matches.forEach(function (el, idx) {
matchesSplit[idx] = el.replace(/[()]/g, '').split('|');
});
// generate result strings
matchesSplit.splice(0, 0, [str]);
cartesianProduct(matchesSplit).forEach(function (el) {
results.push(pattern.formatUnicorn(el));
});
return results;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句