【问题标题】:How to gulp-regex-replace only the first match?如何 gulp-regex-replace 仅第一个匹配项?
【发布时间】:2017-07-07 07:56:55
【问题描述】:

以下是 project.json 文件的内容。我想替换第一次出现的“版本”值。

{
  "title": "Project Title",
  "copyright": "Copyright Info",
  "description": "Project Description",
  "version": "1.0.0",
  "buildOptions": {
    "xmlDoc": true
  },
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    }
  }
}

以下代码使用 gulp-regex-replace 将所有出现的版本值更改为 1.0.1。

var targetVersion= "1.0.1";
gulp.task('replace', function () {
    return gulp.src(['./src/**/project.json'])
        .pipe(bom())
        .pipe(replace({ regex: '\\n\\s\\s\\"version\\"\\:\\s\\"([0-9a-zA-Z.-]+)\\"', replace: `${targetVersion}` }))
        .pipe(gulp.dest('./src'));
});

如何使此代码仅替换第一次出现的版本值?

【问题讨论】:

    标签: javascript gulp gulp-replace


    【解决方案1】:

    gulp-regex-replace 插件使用全局匹配: https://github.com/mikrofusion/gulp-regex-replace/blob/master/index.js#L31

    另一个类似的插件gulp-replace 接受一个自定义的正则表达式对象:

    replace(/__your_pattern__/, targetVersion);
    

    如果模式中没有g 修饰符,JS 将只匹配第一次出现。

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2013-06-15
      • 2020-11-09
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 2020-02-09
      相关资源
      最近更新 更多