JS中的正则表达式(从字符串中选择标签)

时间:2013-03-04 02:12:02

标签: javascript regex

我有这个字符串:

some description +first tag, +second tag (tags separated by commas)
+third tag +fourth tag (tags separated by space)
+tag from new line (it's just one tag)
+tag1+tag2+tag3 (tags can follow each other)

如何从此字符串中选择所有标记名称?

1)标签可以包含多个单词, 2)标签始终以+号开头, 3)标记以下一个标记,换行符或逗号

结束

1 个答案:

答案 0 :(得分:2)

我会试一试:

var str = "some description +first tag, +second tag\n" +
   "+third tag +fourth tag\n" +
   "+tag from new line\n" +
   "+tag1+tag2+tag3";
var tags = str.match(/\+[^+,\n\s].+?(?=\s*[\+,\n]|$)/g);

这会导致tags

[ '+first tag',
  '+second tag',
  '+third tag',
  '+fourth tag',
  '+tag from new line',
  '+tag1',
  '+tag2',
  '+tag3' ]

详细说明:

\+          // Starts with a '+'.
[^+,\n\s]   // Doesn't end immedatedly (empty tag).
.+?         // Non-greedily match everything.
(?=         // Forward lookahead (not returned in match).
  \s*       // Eat any trailing whitespace.
  [\+,\n]|$ // Find tag-ending characters, or the end of the string.
)