How to get all digits after certain character using Regex

Viewed 2207

I have the following string:

@eur99.def.mark.ocal:7342s/mweb/web-style.s.git#v4.2.0

How can I get only the following numbers 4,2,0.

Basically I need all numbers after the dash sign (#);

I've tried this(using look behind pattern), but unsuccessfully.

Regex expression:

(?<=#)\d+

Note: PLEASE, not JS built in string methods

3 Answers

Use parentheses to remember matches, you can access them in the resulting array (indexing from 1, the whole match is stored in 0)

const str = '"web": "@eur99.def.mark.ocal:7342s/mweb/web-style.s.git#v4.22.514"'
const regExp = /#v([0-9]+)\.([0-9]+)\.([0-9]+)/
const res = regExp.exec(str)

console.log(res[1], res[2], res[3]) // 4 22 514

Straight-forward approach:

var regex = /\d/g,
    str = '"web": "@eur99.def.mark.ocal:7342s/mweb/web-style.s.git#v4.2.0"',
    sl = str.substr(str.indexOf('#v')),   // the needed slice
    result = [];

while ((m = regex.exec(sl)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    result.push(m[0]);
}

console.log(result);

you can use indexOf to get the index of #

var str = "@eur99.def.mark.ocal:7342s/mweb/web-style.s.git#v4.2.0";
var num = str.substring(str.indexOf("#") + "#v".length);

Related