0

给定以下字符串:

matrix(1.5, 0, 0, 2, 160, 160)

我想用 替换第一个和第四个值——不管它们是什么——1所以我有:

matrix(1, 0, 0, 1, 160, 160)

如果第一个和第四个值恰好相同,我可以像这样轻松替换它们:

.replace(/1\.5/g, "1")

但这只是在数字上匹配,而不是在位置上,所以如果第一个和第四个值不相同,它就不起作用。我想用 . 替换这两个位置的任何1值。

4

4 回答 4

1

您可以使用正则表达式:

.replace(/[\d.]+(?=(?:, [\d.]+){5}|(?:, [\d.]+){2}\))/g, "1")

正则表达式101演示

只有当它前面还有 5 或 2 个数字直到结束括号时,它才会基本上匹配一个数字(如果有句点)。

于 2013-10-03T19:41:27.533 回答
1

this pattern [\d.]+((,[\s*\d.]+){2},\s*)[\d.]+ will replace 1st and fourth argument regardless of the amount of remaining arguments. Replace with 1$11 Demo

于 2013-10-03T21:39:03.563 回答
0

这是一个不需要任何当前参数类型知识的解决方案:

.replace(/\(([^,]*),\s*([^,]*),\s*([^,]*),\s*([^,]*),\s*(.*?)\)/, "(1, $2, $3, 1, $5)");

This works by matching from the opening paren to the closing paren and capturing each argument in a separate capturing group (except that all remaining arguments are captured in group 5). This is slightly longer than some of the other alternatives but it makes for a very readable replacement.

于 2013-10-03T19:52:06.060 回答
0

Reading left to right, you can always section off the segments you want to replace. Doesn't matter if its 1 or 99:

 #  (\(\s*)[^,]*((?:,[^,]*){2},\s*)[^,]*
 #  Replacement =  $1 + '1' + $2 + '1' 

 ( \( \s* )              # (1), Preamble
 [^,]*                   # 1st value
 (                       # (2), middle 

      (?: , [^,]* ){2}
      , \s* 
 )
 [^,]*                   # 4th value
于 2013-10-03T23:56:43.443 回答