Grunt替换最后出现的匹配字符串

时间:2017-09-06 14:51:17

标签: regex gruntjs

我有一个自定义要求,我需要用空字符串

替换最后一次出现的右括号

如何使用Grunt-replace实现?

在下面的Templates.js文件中,我正在替换

    angular.module('abc.templates', []).run(
with 
return

Templates.js

现在我必须删除第20行下方不必要的右括号。

 angular.module('abc.templates', []).run(['$templateCache', function($templateCache) {
      $templateCache.put("test",
          //
          //
          //
      $templateCache.put("test",
          //
          //
          //
      $templateCache.put("test",
          //
          //
          //
      $templateCache.put("test",
        //
        //
        //
 line 20:   }]);

在上面的Templates.js文件中,我想删除上面第20行中关闭大括号')'的最后一次出现。

有人可以帮助我使用任何正则表达式或其他方法来实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

使用grunt-replace,您可以尝试以下配置:

<强> Gruntfile.js

module.exports = function (grunt) {

  grunt.initConfig({
    replace: {
      templateJs: {
        options: {
          usePrefix: false,
          patterns: [
            {
              match: /angular\.module\('abc\.templates', \[\]\)\.run\(/g,
              replacement: 'return '
            },
            {
              match: /(angular\.module\('abc\.templates', \[\]\)\.run\([\w\W]+?}])(\))(;)/g,
              replacement: '$1$3'
            }
          ]
        },
        files: [
          // Define your paths as necessary...
          {expand: true, flatten: true, src: ['src/template.js'], dest: 'build/'}
        ]
      }
    }
  });

  grunt.loadNpmTasks('grunt-replace');
  grunt.registerTask('default', 'replace:templateJs');
};

其他信息

  1. 解释了match数组中使用的第一个patterns正则表达式模式here。这将处理用angular.module('abc.templates', []).run(
  2. 替换return的第一部分
  3. 解释了match数组中使用的第二个patterns正则表达式模式here。这会从)中删除右括号}]);,最后以}];
  4. 结束

    注意:第二个正则表达式将匹配初始}]);部分后的第一个字符angular.module('abc.templates', []).run(实例,并从中删除)。所以,不幸的是,如果模式}]);出现在函数体的其他地方,那么这将无法满足您的要求。否则它应该没问题。

相关问题