简体   繁体   English

只匹配javascript正则表达式中方括号中的数字,而不匹配上一个单词

[英]Match only digits in square brackets in a javascript regex without matching previous word

I've the following regex in javascript. 我在javascript中使用了以下正则表达式。 I'm trying to match only the first number inside square brackets in a string, as i have to replace it. 我正在尝试仅匹配字符串中方括号内的第一个数字,因为我必须替换它。 This is my code. 这是我的代码。

var str = 'dgt_gallery_item[3][type]'; 
var res = str.match(/^\w+\[(\d+)\]/g);
var rep = str.replace(/^\w+\[(\d+)\]/g, 5 + 1);

The idea is match from start 1 or more alphanumeric chars, then [, then start capturing 1 or more digits, then ]. 这个想法是从1个或多个字母数字字符开始,然后是[,然后开始捕获1个或多个数字,然后是]。

I checked on regex 101 and my code looks correct but when i test it in the browser, it also matches the first word. 我检查了正则表达式101 ,我的代码看起来正确,但是当我在浏览器中对其进行测试时,它也与第一个单词匹配。 How can i skip it? 我该如何跳过呢?

在此处输入图片说明

You can use this regex: 您可以使用此正则表达式:

var rep = str.replace(/(?!\[)\d/, (5+1));

Regex live here . 正则表达式住在这里

Explaining: 解释:

(?!\[)   # the number must be preceded by one '[' character
         # without taking it
\d       # takes a one digit number .. 
         # you can use '\d+' to multiple digits number

Javascript regex engine does not support Look Behind, so you need to do a little tweak here: Javascript正则表达式引擎不支持“向后看”,因此您需要在此处进行一些调整:

var str = 'dgt_gallery_item[3][type]';
var res = str.match(/(^\w+)\[(\d+)\]/g);
var rep = str.replace(/(^\w+)\[(\d+)\]/g, function(combinedMatch, pattern1, pattern2) {
    return pattern1 + "[" + 6 + "]";
});

Output: dgt_gallery_item[6][type] 输出:dgt_gallery_item [6] [type]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM