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 に答える