1

The following string represents a viewmodel property and in this case it has 3 different indices:

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

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".

Thanks a lot

Javier
  • 2,093
  • 35
  • 50

3 Answers3

2

If the pattern is consistent (TEXT[NUMBER].TEXT[NUMBER].TEXT[NUMBER]), you could match all occurrences and then select the second match. A simple example (assuming the above TEXT are always string characters and never contain numbers) would be:

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.

Jack
  • 9,151
  • 2
  • 32
  • 44
2

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
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
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.

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;
    });
}
Community
  • 1
  • 1
Javier
  • 2,093
  • 35
  • 50