简体   繁体   English

正则表达式匹配中间的数字

[英]Regular expression to match number in the middle

The following string represents a viewmodel property and in this case it has 3 different indices: 以下字符串表示viewmodel属性,在这种情况下,它具有3个不同的索引:

PROGRAMA_FASES[ 1 ].PROGRAMA_FASE_REPLICAS[ 0 ].PROGRAMA_FASES.PROGRAMA_PREGUNTAS[ 2 ].Value PROGRAMA_FASES [ 1 ] .PROGRAMA_FASE_REPLICAS [ 0 ] .PROGRAMA_FASES.PROGRAMA_PREGUNTAS [ 2 ]。值

I'm using these functions to increase the first index or the last one. 我正在使用这些功能来增加第一个索引或最后一个索引。

function increment_last(v) {
    return v.replace(/[0-9]+(?!.*[0-9])/, function (match) {
        return parseInt(match, 10) + 1;
    });
}

function increment_first(v) {
    return v.replace(/(\d+)/, function (match) {
        return parseInt(match, 10) + 1;
    });
}

... as you can see i'm using regex to match the number before increasing it. ...如您所见,在增加前,我正在使用正则表达式来匹配数字。

Can you help me with a regex that matches only the index on the middle? 您能帮我一个只匹配中间索引的正则表达式吗? In this case it would be the "0". 在这种情况下,它将为“ 0”。

Thanks a lot 非常感谢

If the pattern is consistent ( TEXT[NUMBER].TEXT[NUMBER].TEXT[NUMBER] ), you could match all occurrences and then select the second match. 如果模式一致( TEXT[NUMBER].TEXT[NUMBER].TEXT[NUMBER] ),则可以匹配所有匹配项,然后选择第二个匹配项。 A simple example (assuming the above TEXT are always string characters and never contain numbers) would be: 一个简单的示例(假设上面的TEXT始终是字符串字符并且从不包含数字)将是:

var number = "PATTERN[0].TO[1].MATCH[2]".match(/\d/g)[1];

If you expect numbers to be mixed in and want to match just the numbers in your brackets, you could update the regex like /\\[\\d\\]/g , and then select the number from within the matched brackets. 如果希望混入数字并只想匹配括号中的数字,则可以更新正则表达式,例如/\\[\\d\\]/g ,然后从匹配的括号中选择数字。

The following regex will capture all three values. 以下正则表达式将捕获所有三个值。

.*\[(\d*)*\].*\[(\d*)*\].*\[(\d*)*\].*

You can access them in the following example 您可以在以下示例中访问它们

var myString = "PROGRAMA_FASES[1].PROGRAMA_FASE_REPLICAS[0].PROGRAMA_FASES.PROGRAMA_PREGUNTAS[2].Value";
var myRegexp = /.*\[(\d*)*\].*\[(\d*)*\].*\[(\d*)*\].*/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // Will output 1

Thank you both for your answers which gave me a better approach and another way of thinking a solution. 谢谢您的回答,这些回答为我提供了更好的方法以及解决方案的另一种思路。

Finally I found this answer https://stackoverflow.com/a/7958627/1532797 which gives an excellent solution to this and can be used for many other purposes. 最后,我找到了这个答案https://stackoverflow.com/a/7958627/1532797 ,它提供了一个极好的解决方案,并且可以用于许多其他目的。

In my case I can simply increment the desired index position calling the function like this: 就我而言,我可以简单地增加所需的索引位置,就像下面这样调用函数:

function increment_index(v, i) {
    return replaceNthMatch(v, /(\d+)/, i, function (val) {
        return parseInt(val, 10) + 1;
    });
}

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

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