最后一个冒号后匹配字符串
问题描述:
我有以下字符串
foo:21,bar:11
foo: 21, bar: 11
其中foo和bar不是常量,所以我试图匹配最后:(冒号)字符后的所有数字。
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?
谢谢!
答
使用否定正则表达式可以使用此正则表达式:
Using negative regex you can use this regex:
/\d+(?![^:]*:)/g
(?![^:] *:)
是负面预测断言没有:
在我们匹配的数字之前。
(?![^:]*:)
is negative lookahead to assert that there is no :
ahead of digits we are matching.
代码演示:
var myString = 'foo: 21, bar: 11';
console.log(myString.match(/\d+(?![^:]*:)/g));