问题
gulp-replace 0.5.4
Current via gulp and rev:
<link rel="stylesheet" href="assets/styles/app-3c224ff086.css">
Goal:
<link rel="stylesheet" href="assets/styles/app-3c224ff086.css" media="screen">
Result:
<link rel="stylesheet" href="$1" media="screen">
Initial test was: https://regex101.com/r/miM7TN/1 . I might have linked the test with a capture group of $0, but in my project I am using capture group 1.
In my gulp task the following is added:
var regex = /\"assets\/styles\/app-+.*\"/;
var subst = `$1 media="screen"`;
.pipe(replace(regex, subst))
My string, to include start and end quotes, is being found. Instead of a capture group I am getting a literal $1. How do I get the actual value of the capture group? The gulp-replace documentation shows a replace value '$1foo'. Similar questions on SO show '$1' and "$1", and I am not yet seeing the difference to my situation. I've tried back-ticks, single quotes, and double quotes.
回答1:
The $1
backreference refers to a capturing group with ID 1, the text captured with the first (...)
in your pattern.
You must use
var regex = /("assets\/styles\/app-+.*")/;
for $1
to "work" the same way as $&
(backreference to the whole match value).
回答2:
Your can use a callback as the second parameter in gulp-replace. The function was loop over each capture group. Here's an example where I am converting camelCase variables to css notation
.pipe(replace(/([A-Z])/g, function(match){
return '-'+match.toLowerCase()
}))
{camelCase1: 1, camelCase2: 2}
Becomes camel-case1 and case-case2
来源:https://stackoverflow.com/questions/42663767/how-to-use-a-capture-group-with-gulp-replace