如何使用正则表达式查找两个租船人之间句子中的所有单词?

时间:2019-01-30 07:48:21

标签: javascript regex

我正在尝试使用正则表达式提取两个词组之间存在的句子中的所有作品

var sentence = "i would like to extract $#word1#$ ,$#word2#$ and $#word3#$"
/\$\#(.*?)\#\$/g.exec(sentence);

输出为

["$#word1#$", "word1"]

预期输出为

['word1','word2','word3']

1 个答案:

答案 0 :(得分:-1)

我尝试使用match函数,但是得到了数组([[“ $#word1#$”,“ $#word2#$”,“ $#word3#$”])

因此,对于您而言,我使用了函数replace函数。这是代码:

const subStrings = [];
sentence.replace(/\$\#(.+?)\#\$/g, (str, word) => subStrings.push(word));

console.log(subStrings);

输出subStrings['word1','word2','word3']

其他信息: 如果要使用exec函数,请看以下示例:

var regex1 = RegExp('foo*','g');
var str1 = 'table football, foosball';
var array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
  // expected output: "Found foo. Next starts at 9."
  // expected output: "Found foo. Next starts at 19."
}

有关replace函数的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

有关exec函数的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec