下面我试图用另一个字符串moduleName
替换replacementModule
字符串。
var replacementModule = 'lodash.string' // cheeky
var moduleName = 'underscore.string'
var pattern = new RegExp('^' + moduleName + '(.+)?')
var match = definition.match(pattern)
var outcome = replacementModule + match[1]
但是现在一个完全不同的模块也匹配。
underscore.string.f/utils
//希望不做任何更改underscore.string.f
//希望不做任何更改underscore.string
// => lodash.string underscore.string/utils
// => lodash.string / utils的我如何与/
匹配,以及我期望的结果如何?
答案 0 :(得分:1)
你需要做至少3件事:
match
是否为null
($|/.*)
作为捕获组1,以匹配字符串的结尾或/
后跟0或更多字符。
RegExp.escape = function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
function runRepl(definition, replacementModule, moduleName) {
var pattern = RegExp('^' + RegExp.escape(moduleName) + '($|/.*)');
// ^------------^ ^------^
var match = definition.match(pattern);
if (match !== null) { // Check if we have a match
var outcome = replacementModule + match[1];
document.write(outcome + "<br/>");
}
else {
document.write("N/A<br/>");
}
}
runRepl("underscore.string.f/utils", "lodash.string", "underscore.string");
runRepl("underscore.string.f", "lodash.string", "underscore.string");
runRepl("underscore.string", "lodash.string", "underscore.string");
runRepl("underscore.string/utils", "lodash.string", "underscore.string");
&#13;
必须使用转义来匹配.
内的文字moduleName
和($|/)(.+)?
假设在字符串结尾后可能存在某些内容。此外,(.+)?
(1个或多个字符)实际上与.*
相同,后者更短且更易于阅读。