字符串替换模块定义

时间:2015-08-25 21:13:43

标签: 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 个答案:

答案 0 :(得分:1)

你需要做至少3件事:

  1. 转义传递给RegExp的字符串变量
  2. 使用前检查match是否为null
  3. 正则表达式应包含($|/.*)作为捕获组1,以匹配字符串的结尾或/后跟0或更多字符。
  4. 
    
    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;
    &#13;
    &#13;

    必须使用转义来匹配.内的文字moduleName($|/)(.+)?假设在字符串结尾后可能存在某些内容。此外,(.+)?(1个或多个字符)实际上与.*相同,后者更短且更易于阅读。