Trost
Trost

Reputation: 109

Do calculations on regex capture group in gulp

I need to write a script to restructure some code to new syntax, while also multiplying\dividing some of the present values.

TLDR:

For example i want to turn:

oldFunction(3, "text");
oldSize = 3;

into

newfunction("text", 3);
newSize = 6; //notice that this is oldSize*2

I managed the replace and reorder part with gulp-replace and regex, but I don't know how to multiply numbers in regex capture groups.

FULL:

More detailed example:

font size = 34px;
text position = {5, 42};

I use regex and gulp-replace to restructure it into new syntax:

.pipe($.replace(/font size = (.+)px;\ntext position = {(.+), (.+)}/g, 'createText($2, $3, $1);'))

And I get:

createText(5, 42, 34);

All good - old numbers are now in all the right order!

Now, the problem: Can I somehow do basic math manipulations (multiplication, division) to the old numbers before replacing?

Also. If there is more practical tool for such task - I'll be happy to use it.

Upvotes: 1

Views: 217

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626816

You may use a regular anonymous callback method inside .replace to be able to manipulate group values.

.pipe($.replace(/font size = (.+)px;\ntext position = {(.+), (.+)}/g, function($0,$1,$2,$3) { 
    return 'createText(' + $2 + ', ' + $3 + ', ' + $1*2 + ');'; 
 }))

The last value will be multiplied by 2.

You should consider using a digit matching pattern ([0-9]+) instead of a wildcard-like .+ (where . matches any char but a line break char) for that kind of code to work safely.

Upvotes: 2

Related Questions