【问题标题】:Do calculations on regex capture group in gulp在 gulp 中对正则表达式捕获组进行计算
【发布时间】:2017-05-15 22:31:05
【问题描述】:

我需要编写一个脚本来将一些代码重组为新的语法,同时还要乘除一些当前值。

TLDR:

比如我想转:

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

进入

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

我使用 gulp-replace 和 regex 管理替换和重新排序部分,但我不知道如何将 regex 捕获组中的数字相乘。

已满:

更详细的例子:

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

我使用 regex 和 gulp-replace 将其重组为新语法:

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

我得到:

createText(5, 42, 34);

所有好的 - 旧号码现在都按正确的顺序排列!

现在,问题是:我能否在替换之前对旧数字进行基本的数学运算(乘法、除法)?

还有。如果有更实用的工具来完成此类任务 - 我会很乐意使用它。

【问题讨论】:

  • 尝试用function($0,$1,$2,$3) { return $2 + $3 + $1*2; }替换'createText($2, $3, $1);'
  • @Wiktor 是的。这行得通,谢谢!也许您应该将其发布为答案?

标签: javascript regex npm gulp gulp-replace


【解决方案1】:

您可以使用普通的anonymous callback method inside .replace 来操作组值。

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

最后一个值将乘以 2。

您应该考虑使用数字匹配模式 ([0-9]+) 而不是类似通配符的.+(其中. 匹配除换行符以外的任何字符),以使此类代码安全运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    相关资源
    最近更新 更多