在特定字符串之后使用 JavaScript 正则表达式找到的增量数

我真的尽力了,但不知何故我无法让它发挥作用。


我有以下 SVG 路径数据:


var str = "m 0.05291667,1.7345817 h 0.16018 V 0.05291667 H 1.4943367 v 0.56054601 l -0.16015,0.16017899 0.16015,0.16012501 V 1.4943397 H 0.69354668 V 1.2541247 H 1.2540967 V 1.0138577 L 1.0939467,0.90175268 H 0.69354668 v -0.240215 H 1.0939467 l 0.16015,-0.128138 V 0.29313166 H 0.45330668 V 1.7345817 H 1.6544867"

我想要实现的是获取每个值之后的所有值H并将该值增加一个数字(假设为2)。


我目前拥有的正则表达式选择所有这些数字:


/(?<=H )(.*?)(?= )/g

但是,我不知道现在如何使用该replace()函数增加这些数字。


这是我目前拥有的:


var H = str.match(/(?<=H )(.*?)(?= )/g)


for (var j=0; j<H.length; j++) {

    str = str.replace(/(?<=H )(.*?)(?= )/g, function (match, i, original) {

            nth++;

            return (nth == j) ? (parseFloat(H[j]) + 2).toString() : match;

    });

}

但它没有给我想要的结果。


我能做什么?


PIPIONE
浏览 206回答 3
3回答

冉冉说

使用match参数var str = "m 0.05291667,1.7345817 h 0.16018 V 0.05291667 H 1.4943367 v 0.56054601 l -0.16015,0.16017899 0.16015,0.16012501 V 1.4943397 H 0.69354668 V 1.2541247 H 1.2540967 V 1.0138577 L 1.0939467,0.90175268 H 0.69354668 v -0.240215 H 1.0939467 l 0.16015,-0.128138 V 0.29313166 H 0.45330668 V 1.7345817 H 1.6544867"str = str.replace(/(?<=H )(.*?)(?= )/g, function(match, i, original) {&nbsp; return parseFloat(match) + 2});console.log(str)

慕码人8056858

您可以使用 replace 中的回调函数并使用 2 个捕获组。请注意,您不需要后视(?<=,而且 Javascript 尚未广泛支持后视。您可以使用以下方法匹配数字和大写字母H:\b(H&nbsp;)(\d+(?:\.\d+)?)\b(H )捕获第 1 组、匹配H和前面有单词边界的空格(捕获组 2\d+(?:\.\d+)?&nbsp;匹配 1+ 位数字,可选择匹配一个点和 1+ 位数字)&nbsp;关闭群组正则表达式演示在替换中使用 2 个捕获组,并为组 2 中捕获的内容添加一个数字。let pattern = /\b(H )(\d+(?:\.\d+)?)/g;var str = "m 0.05291667,1.7345817 h 0.16018 V 0.05291667 H 1.4943367 v 0.56054601 l -0.16015,0.16017899 0.16015,0.16012501 V 1.4943397 H 0.69354668 V 1.2541247 H 1.2540967 V 1.0138577 L 1.0939467,0.90175268 H 0.69354668 v -0.240215 H 1.0939467 l 0.16015,-0.128138 V 0.29313166 H 0.45330668 V 1.7345817 H 1.6544867"str = str.replace(pattern, function(_, g1, g2) {&nbsp; return g1 + (Number(g2) + 2);});console.log(str);

喵喵时光机

const str = "m 0.05291667,1.7345817 h 0.16018 V 0.05291667 H 1.4943367 v 0.56054601 l -0.16015,0.16017899 0.16015,0.16012501 V 1.4943397 H 0.69354668 V 1.2541247 H 1.2540967 V 1.0138577 L 1.0939467,0.90175268 H 0.69354668 v -0.240215 H 1.0939467 l 0.16015,-0.128138 V 0.29313166 H 0.45330668 V 1.7345817 H 1.6544867"const regex = new RegExp('H\\s*([\\d\\.]+)', 'g');let matches;while ((matches = regex.exec(str))) {&nbsp; &nbsp; const found = matches[1];&nbsp; &nbsp; const newValue = parseFloat(found) + 2.0;&nbsp; &nbsp; console.log(newValue);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript