Regular expression to detect and update a string (useful for updating the file version in AssemblyInfo.cs)

I have a string of this format

1.0.x.0

      

I need to write a regex in javascript that automatically increments x

- how to do that?

Note that the specified string will always be in this format - there is no need to validate the format ...

+1


a source to share


2 answers


Try the following:



"1.0.123.0".replace(/(\d+\.\d+\.)(\d+)(\.\d+)/, function($0, $1, $2, $3) {
    return $1 + (parseInt($2) + 1) + $3;
});

      

+8


a source


Why should it be a regular expression? The designations are consistent and change slightly; no regex required.

function incrementStrN(str) {
    var split = str.split('.');
    split[2]++;
    return split.join('.');
}
incrementStrN("1.0.123.0"); // Returns "1.0.124.0"

      



I know it doesn't look very pretty, but it's faster than using a regular expression; plus it is easier to configure; for example, you can implement it in such a way that the section to be enlarged can be changed: (see ) @param sec

function incrementStrN(str, sec) {
     var split = str.split('.');
     split[sec-1]++;
     return split.join('.');
}

incrementStrN("1.0.123.0", 1); // Returns "2.0.123.0"
incrementStrN("1.0.123.0", 3); // Returns "1.0.124.0"

      

+2


a source







All Articles