Reputation: 670
I want to replace a string using grunt-string-replace. Unfortunately my RexEx is not working, even when matching perfectly in regex101?
This pattern shall match all CSS links:
<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
This is the replace part in my Gruntfile.js (and it works when using it without regex):
'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'
}]
}
}
},
Maybe there is a special start/end/escape Pattern that is expected by Grunt?
Upvotes: 1
Views: 621
Reputation: 97718
I searched online for "grunt string-replace", based on the section of the file you showed. This led me to the grunt-string-replace NPM page, which contains an example:
options: {
replacements: [{
pattern: /\/(asdf|qwer)\//ig,
replacement: '"$1"'
}, {
pattern: ',',
replacement: ';'
}]
}
Note that this is not JSON, it is an actual JavaScript file (Gruntfile.js
, not Gruntfile.json
), so the regex is not a string containing the pattern to be matched, but a JavaScript regex literal. MDN is a great resource for learning JS, and the MDN page about regular expressions explains this literal syntax in detail.
In short, it needs to be enclosed in /whatever/
instead of 'whatever'
.
Upvotes: 2