下面我尝试将 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.stringunderscore.string/utils
//=> lodash.string/utils
我如何匹配/
,以及我期望的结果如何?
最佳答案
您至少需要做三件事:
- 转义传递给正则表达式的字符串变量
- 使用前检查
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");
必须进行转义才能匹配 moduleName
内的文字 .
和 ($|/)(.+)?
假定可能存在某些内容在字符串末尾之后。此外,(.+)?
(1 个或多个字符)实际上与 .*
相同,后者更短且更易于阅读。
关于javascript - 字符串替换模块定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32214201/