Grunt 正则表达式语法

Grunt RegEx Syntax

我想用 grunt-string-replace 替换一个字符串。不幸的是,即使在 regex101 中完美匹配,我的 RexEx 也无法正常工作?

此模式应匹配所有 CSS 个链接:

<link href=\"css\/[a-zA-Z\-]+\.css\"[a-zA-Z=\"\/ ]+>

<link href="css/normalize.css" >
<link href="css/normalize.css" rel="stylesheet" type="text/css">
<link href="css/components.css" rel="stylesheet" type="text/css">
<link href="css/style-sheet.css" rel="stylesheet" type="text/css">

https://regex101.com/r/aY9hY0/21

这是我的 Gruntfile.js 中的替换部分(在没有正则表达式的情况下使用它时它有效):

 'string-replace': {
        dist: {
            files: [{
                expand: true,
                cwd: '../src',
                src:  '**/*.html',
                dest: '../process/html'
            }],
            options: {
                saveUnchanged: true,
                replacements: [{
                    pattern:     '<link href=\"css\/[a-zA-Z\-]+\.css\"[a-zA-Z=\"\/ ]+>',
                    replacement: 'asdf'
                }]
            }
        }
    },

也许 Grunt 需要一个特殊的 start/end/escape 模式?

我根据您显示的文件部分在线搜索了 "grunt string-replace"。这让我找到了 the grunt-string-replace NPM page,其中包含一个示例:

options: {
  replacements: [{
    pattern: /\/(asdf|qwer)\//ig,
    replacement: '""'
  }, {
    pattern: ',',
    replacement: ';'
  }]
}

请注意,这不是 JSON,它是一个实际的 JavaScript 文件(Gruntfile.js,而不是 Gruntfile.json),因此正则表达式不是包含要匹配的模式,但是 JavaScript 正则表达式文字。 MDN 是学习 JS 的绝佳资源,the MDN page about regular expressions 详细解释了这种文字语法。

总之需要用/whatever/ 括起来,而不是 'whatever'.