首页 > 解决方案 > 如何通过正则表达式在连续标记之间抓取单词?

问题描述

我正在尝试单独解析和:hello::world:抓取。不幸的是,结果如下:helloworld

const str = ':hello::world:'
const matches = str.match(/\:[^\s]+\:/g)
console.log(matches) // [':hello::world:']

标签: javascriptregex

解决方案


您的正则表达式匹配任何字符串,除了导致匹配所有字符串的空格。所以你需要匹配任何字符串,除了:

const str = ':hello::world:'
const matches = str.match(/[^:]+/g);
console.log(matches); 

请注意,您可以在没有正则表达式的情况下完成这项工作。只需按:分隔符拆分字符串并使用删除空项目.filter()

const str = ':hello::world:'
const matches = str.split(':').filter(v=>v!='');
console.log(matches) 


推荐阅读