js区分正则expression式捕获组
javascript / node.js中有一种方法来区分由正则expression式创build的捕获组吗? 例如,正则expression式: /([AZ]+\[[^\]]+])|(\d+)/g
: 9 and 4687 matches but not NUMBER[9] or NUMBER[9568] However, [401] should match...
将创build两个捕获组:
- 第1组:第NUMBER [9]和NUMBER [9568]
- 第2组:9,4687和401
我想要的是在我的文字上添加NUMBER[]
周围的标签NUMBER[]
。 有没有办法像text.replace(regexp, 'NUMBER[$&]', SECOND_GROUP)
?
编辑:输出将是NUMBER[9] and NUMBER[4687] matches but not NUMBER[9] or NUMBER[9568] However, [NUMBER[401]] should match...
您可以在String#replace()
使用callback方法作为replace参数,以检查特定的组是否匹配,并在匿名方法内执行适当的replace逻辑:
var regex = /([AZ]+\[[^\]]+])|(\d+)/g; var str = `9 and 4687 matches but not NUMBER[9] or NUMBER[9568] However, [401] should match...`; var res = str.replace(regex, function($0,$1,$2) { return $2 ? "NUMBER[" + $2 + "]" : $0; // If Group 2 matched, use special value, else paste back the match }); console.log(res);