从字符串中提取单词并拆分

时间:2019-08-23 16:04:04

标签: javascript regex

我有一个问题。我的字符串很长,也包含特殊字符。我想使用正则表达式提取单词并使用split函数获取所需的输出。

["one", "two", "three", "four", "five"]

我尝试了这两种不同的方法。

var fill = "|@!../::one:://::two:://::three:://four:://five|".match("([0-9a-zA-Z_]").split(" ");

var fill = "|@!../::one:://::two:://::three:://four:://five|".toString().split(" "), function(a) { return /[0-9a-zA-Z_]/.test(a)};
  

.match(...)。split不是函数

我是收到的错误消息。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您要获取所有匹配项。这可以通过RegExp的exec()方法来完成:

const matchWords = /[a-z0-9_]+/gi;
const results = [];
const testStr = "|@!../::one:://::two:://::three:://four:://five|";
let match = null;
while(match = matchWords.exec(testStr)) {
    results.push(match[0]);
}
console.log(results);

要了解其原因和工作方式,请参见RegExp上的MDN文档。