2015-11-09 25 views
0

我正在尋找一種方法來輸出距離(空白分隔的詞的量)以在兩個給定的控制檯之間進行控制。考慮以下.txt輸入:計算示例文本的2個給定詞之間的距離

[SEP] Today I went to school for the first time . [/SEP] [SEP] Everyone was excited to see me ! [/SEP] 

我現在需要得到在這種情況下[SEP][/SEP]之間的距離將是9和6

房地產.txt輸入您可能已經猜到是更長的時間。

UPDATE:我的做法至今(分成數組):

var text = "[SEP] Today I went to school for the first time . [/SEP] [SEP] Everyone was excited to see me ! [/SEP]"; 
var textArray = text.split(/\[SEP\]|\[\/SEP\]/); 

UPDATE:匹配在註釋的正則表達式提供

var text = "[SEP] Today I went to school for the first time . [/SEP] [SEP] Everyone was excited to see me ! [/SEP]"; 
var matchText = text.match("\[[A-Z]+\]([^[]+)\[\/[A-Z]+\]"); 

UPDATE:使用.exec()

var myText = \[[A-Z]+\]([^[]+)\[\/[A-Z]+\].exec('[SEP] Today I went to school for the first time . [/SEP] [SEP] Everyone was excited to see me ! [/SEP]') 
+0

SEP標籤可以得到多層次? (eq [bla] [sep] bla2 bla3 –

+0

@ mihai.ciorobea好點,但在我的情況下,他們不 – Ilja

+0

@Tushar我的壞,我現在添加的代碼,以將單詞放入數組 – Ilja

回答

1

嘗試使用split分割文本。這將提供SEP之間的單詞列表。

"[SEP]this is [/SEP] an interesting [SEP] thing[/SEP]".split(/\[SEP\]|\[\/SEP\]/) 

之後,您可以用確定

words.length - words.replace(/ /g,'').length 

完整的解決方案各組大小:

var wordGroups = "[SEP]this is [/SEP] an interesting [SEP] thing[/SEP]".split(/\[SEP\]|\[\/SEP\]/) 
wordGroups.forEach(function(wordGroup) { 
    wordGroup = wordGroup.trim() 
    if (wordGroup.length == 0) { 
     return 
    } 
    var nrOfWords = wordGroup.length - wordGroup.replace(/ /g,'').length + 1 
    console.log("\"" + wordGroup + "\" has " + nrOfWords + " words") 
})