2013-03-04 76 views
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)標籤與任何一個標籤,或換行或逗號結尾

+0

我試過按行分割字符串,然後按','。所以我有一些子串。然後我需要從每個子字符串中提取標籤。這比從最初的字符串有點容易,但我仍然不知道如何去做:) – Ildar 2013-03-04 02:18:30

+0

那麼你會得到什麼結果?類似於{first:「tag」,second:「tag(標籤分隔的標籤)」,第三個:「tag」,第四個:「tag(標籤以空格分隔)」,tag:「from new line(它只是一個標籤)「,tag1tag2tag3:」(標籤可以跟着彼此)「} – OJay 2013-03-04 02:38:01

+0

只是一個普通的標籤數組 – Ildar 2013-03-04 02:44:04

回答

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. 
) 
+0

它不抓住最後一個標籤」tag3「 – Ildar 2013-03-04 02:52:47

+0

好吧,我可以在字符串的末尾追加一個\ n :) – Ildar 2013-03-04 02:54:08

+0

您需要在您的前瞻中添加'$'(即'(?= \ s *([\ +,\ n] | $))'),但是+1 – mVChr 2013-03-04 02:54:33