【问题标题】:regex find all occurence of content containing numbers surrounded by double asterisk正则表达式查找包含双星号包围的数字的所有内容
【发布时间】:2018-08-21 21:29:33
【问题描述】:

我有这个: 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

标签: javascript regex match


【解决方案1】:

你可以使用

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

regex demo

详情

  • \*{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)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2014-01-14
    • 2016-12-07
    相关资源
    最近更新 更多