使用 javascript 正则表达式替换和递增整数值 [英] replace and increment integer value using a javascript regex

查看:39
本文介绍了使用 javascript 正则表达式替换和递增整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下字符串

XXXX Units[4].Test XXXX

我想用 Unit[x+1] 替换每次出现的 Unit[x].
我正在尝试使用正则表达式来实现这一点,因为名称 Units 需要首先按字面匹配.

I would like to replace each occurrence of Unit[x] with Unit[x+1].
I am trying to achieve this using a regular expression, as the name Units needs to be literally matched first.

我正在尝试这样的事情:

I am trying something like this:

test.replace(/(?:Units\[|\_+)(\d+)/g, function(m, i) { return parseInt(m) + 1 })

我的问题是,如果没有正面回顾,我似乎只能匹配数字.我试图以这样一种方式构建正则表达式,即只有数字构成捕获组的一部分,因此我可以替换它们.

My problem is that without positive lookbehind I cannot seem to match only the digits. I am trying to build the regex in such a way that only the digits form part of the capture group, and I can therefore replace them.

在 c# 中很容易做到,但 javascript 匹配函数的工作方式略有不同.

It's easy to do in c#, but the javascript match function works a little differently.

尽管 (?: 的非捕获规范,Units[ 似乎构成了匹配的一部分.由于 javascript 不支持后视,我不知所措关于如何完成这个.

Despite the non capture specification of (?: the Units[ seems to form part of the match. Since javascript does not support look behind, I am at a loss as to how to complete this.

推荐答案

您需要在编号之前对零件进行分组,并在以后使用该反向引用替换:

You need to group the part before number and use that back-reference in replacement later:

test = test.replace(/(Units\[)(\d+)/ig, function($0, $1, $2) {
      return $1 + (parseInt($2)+1); })

//=> XXXX Units[5].Test XXXX

注意在回调函数中使用$1$2,其中$1代表值Units[>$2 是它后面的数字.

Note use of $1 and $2 in the callback function where $1 represents value Units[ and $2 is the number after it.

这篇关于使用 javascript 正则表达式替换和递增整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆