0

我有这个字符串:

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) 标签以下一个标签、换行符或逗号结尾

4

1 回答 1

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.
)
于 2013-03-04T02:38:24.117 回答