gpt4 book ai didi

javascript - 字符串替换模块定义

转载 作者:行者123 更新时间:2023-11-27 23:56:33 26 4
gpt4 key购买 nike

下面我尝试将 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

我如何匹配/,以及我期望的结果如何?

最佳答案

您至少需要做三件事:

  1. 转义传递给正则表达式的字符串变量
  2. 使用前检查match是否为null
  3. 正则表达式应包含 ($|/.*) 作为捕获组 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com