如何使用javascript查找匹配的文本

时间:2011-12-13 08:17:12

标签: javascript regex

如何使用正则表达式提取“text:”后面的单词?输入类似于:

some string some string (text:the_word_i_want_to_get some string) some string
some string some string (text:next_word_i_want_to_get some string) some string

,输出应为:

["the_word_i_want_to_get", "next_word_i_want_to_get"]

1 个答案:

答案 0 :(得分:0)

您可以匹配第一个出现的单词,如下所示:

var input = "some string...",// Assume this is what you wrote in your question.
    match = input.match(/text:(\w+)/)[1];

要获得所有匹配项,您可以将其置于循环中:

while (/text:(\w+)/) {
  matches.push(input.match(/text:(\w+)/)[1]);
  input = input.replace(/text:(\w+)/, "");
}