开发者

Need help with Javascript Regular Expressions - Splitting text

I have a string that represents a list of tags separated by space. It may look like this:

Australia 2010 David November Family

If a tag contains at least one space, it must be quoted. So the string can be:

"Best Friends" "My Pictures" Wow "Very Nice Photo" University

Quotes are also allowed for single words. For example:

"Good One" Fantastic "February" "My Family" "Friends"

The question is:

How would you get an array of tags from the string ?

For example, from the third string I would like to get the following array:

arr[0] = "Good One"
arr[1] = "Fantastic"
arr[2] = "February"
arr[3] = "My Family"
arr[4] = "Friends"开发者_开发技巧

If the string is not in the right format, I would like to know about it (for example: to get empty array as a result).


You can use a regular expression like /"[^"]+"|\w+/ to match the tags. To get an array containing all the matches without quotation marks, you can use something like

var re = /"[^"]+"|\w+/g;
var result = [];
var match;
while(match = re.exec(input))
    result.push(match[0].replace(/"/g, ""));

If you don't have to remove the quotation marks, you can just use

var result = input.match(re);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜