从正则表达式中获取int

Get int from REGEX

本文关键字:int 获取 正则表达式      更新时间:2023-09-26

我想使用REGEX在字符串中获得数字,但似乎不起作用。

我的字符串:<p>My awesome calendar</p> [calendar last="4"] !

Regex: /'[calendar last="[1-9]"]/g

Result: [calendar last="[1-9]"]

我想知道最近事件的数量…应为:4

您可能需要一个捕获组,使用括号

/'[calendar last="([1-9])"]/g

然后可以使用exec

访问捕获组的结果

var str = '<p>My awesome calendar</p> [calendar last="4"] !'
var regex = /'[calendar last="([1-9])"']/g
console.log(regex.exec(str)[1]) // 0 is the entire match, 1 is the first group

只需在需要的地方使用()符号,然后使用replace来获取值:

'<p>My awesome calendar</p> [calendar last="4"] !'.replace(/.*'[calendar last="([1-9])"'].*/g, '$1');