[英]Regular expressions in JS (select tags from string)
I have this string: 我有这个字符串:
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)
How can I select all tag names from this string? 如何从此字符串中选择所有标记名称?
1) Tag can contain several words, 2) tag always starts with + sign, 3) tag ends with either next tag, or newline, or comma 1)标签可以包含多个单词,2)标签始终以+号开头,3)标签以下一个标签,换行符或逗号结尾
I'd give this a shot: 我试试看:
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);
this results in tags
with this: 这导致tags
:
[ '+first tag',
'+second tag',
'+third tag',
'+fourth tag',
'+tag from new line',
'+tag1',
'+tag2',
'+tag3' ]
To elaborate: 详细说明:
\+ // 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.
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.