match string after the last colon

2020-04-13 17:38发布

i have the following string

foo: 21, bar: 11

where foo and bar are not constants, so I'm trying to match all the digits after the last ":"(colon) character.

const myString = 'foo: 21, bar: 11'
myString.match(/\d+/g).shift().join() -> 11

can i do the same just with pure regex?

thanks!

3条回答
霸刀☆藐视天下
2楼-- · 2020-04-13 18:13

Using negative regex you can use this regex:

/\d+(?![^:]*:)/g

RegEx Demo

(?![^:]*:) is negative lookahead to assert that there is no : ahead of digits we are matching.

Code Demo:

var myString = 'foo: 21, bar: 11';
console.log(myString.match(/\d+(?![^:]*:)/g));

查看更多
够拽才男人
3楼-- · 2020-04-13 18:17

var myString = 'foo: 21, bar: 11';
console.log(myString.replace(/(.)*\:\s?/,''));

查看更多
聊天终结者
4楼-- · 2020-04-13 18:35

You may use either of the two solutions:

This one will match up to the last : and grab the digits after 0+ whitespaces:

var s = "foo: 21, bar: 11";
var m = s.match(/.*:\s*(\d+)/);
if (m !== null) {
  console.log(m[1]);
}

And this one will find a : followed with 0+ whitespaces, then will capture 1+ digits into Group 1 and then will match 0+ chars other than : up to the end of string.

var s = "foo: 21, bar: 11";
m1 = s.match(/:\s*(\d+)[^:]*$/);
if (m1 !== null) {
  console.log(m1[1]);
}

查看更多
登录 后发表回答