javascript - 字符串替换模块定义

标签 javascript regex string

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

相关文章:

javascript - 将复选框从一组移动到另一组

javascript - React 列表的无限滚动

javascript - responseText 数组无法正确解析

javascript 正则表达式 iso 日期时间

regex - 使用正则表达式匹配版本号,同时排除带下划线的条目

C++ 字符串与 vector <char>

r - 在 R 中的字符串中不存在的数据框中创建列

swift - 无法在 swift ("if"或可能 "while"中创建正确的函数)

javascript - Google App Script 声明中的超链接已删除

Javascript正则表达式匹配数字零或任何大于零的整数