如何使用Regex [duplicate]获取特定字符后的所有数字

时间:2022-08-22 13:12:29

This question already has an answer here:

这个问题已经有了答案:

I have the following string:

我有以下字符串:

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

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

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

我怎么能只得到下面的4 2 0。

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

基本上,我需要所有的数字后面的破折号(#);

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

我尝试过这个(使用look behind模式),但没有成功。

Regex expression:

正则表达式:

(?<=#)\d+

(? < = #)\ d +

Note: PLEASE, not JS built in string methods

注意:请不要在string方法中构建JS

3 个解决方案

#1


1  

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

使用圆括号来记住匹配项,您可以在结果数组中访问它们(从1开始建立索引,整个匹配项存储在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

#2


1  

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);

#3


0  

you can use indexOf to get the index of #

您可以使用indexOf获取#的索引

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

#1


1  

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

使用圆括号来记住匹配项,您可以在结果数组中访问它们(从1开始建立索引,整个匹配项存储在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

#2


1  

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);

#3


0  

you can use indexOf to get the index of #

您可以使用indexOf获取#的索引

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