正则表达式查找所有包含双星号括起来的数字的内容



>我有这个:const str = "hello **Tom**, it's currently **19h25**. Here is **19** things found during the **last 2 hours** by **John1**"

我需要找到所有出现的内容,其中有数字,用双星号括起来。

我想str.match(regex)['19h25', '19', 'last 2 hours', 'john1']回来。但不**Tom**因为内容中没有数字。

/*{2}(.*d)*{2}/g尝试过这样的正则表达式,但它不起作用。

编辑:两个**内都没有星号*

您可以使用

/*{2}([^d*]*d[^*]*)*{2}/g

查看正则表达式演示

  • *{2}-**子字符串
  • ([^d*]*d[^*]*)- 第 1 组:
    • [^d*]*- 除数字和*以外的 0+ 字符
    • d- 数字
    • [^*]*- 除*以外的 0+ 个字符
  • *{2}-**子字符串

JS演示:

const str = "hello **Tom**, it's currently **19h25**. Here is **19** things found during the **last 2 hours** by **John1**";
const rx = /*{2}([^d*]*d[^*]*)*{2}/g;
let m, res = [];
while (m = rx.exec(str)) {
res.push(m[1]);
}
console.log(res);
// or a one liner
console.log(str.match(rx).map(x => x.slice(2).slice(0, -2)));

相关内容

最新更新