2014-08-28 24 views
1

我試圖匹配未由字符串中的點分隔的單詞。
因爲在JavaScript中沒有後向關係,所以我一直在努力解決這個問題,並且無法讓它工作。Javascript正則表達式匹配由空格分隔但不包含點的字符串

的TestString 1:'one two three.four five six.seven eight'
應該匹配:'one', 'two', 'five', 'eight'

的TestString 2:'one.two three four.five six seven.eight'
應該匹配:'three', 'six'

更新:
的TestString 3:'one.two three four five six seven.eight'
應該匹配:'three', 'four', 'five', 'six'

到目前爲止,我有(|^)(\w+)(|$),這有點適用於測試字符串2,但不能匹配'two'

有沒有什麼辦法可以用正則表達式來做這件事,還是應該把它拆分成一個數組然後走?

回答

3

用正則表達式(|^)\w+(?= |$)得到匹配的字符

'one two three.four five six.seven eight'.replace(/(|^)\w+(?= |$)/g, '$1TEST') 

或者沒有正則表達式(也許更易讀)

'one two three.four five six.seven eight'.split(' ').map(function(item) { 
    if(item.indexOf('.') < 0) 
     return 'TEST'; 
    return item; 
}).join(' ') 
+0

這是完美的!謝謝!這個?=做什麼? – 2014-08-28 10:54:17

+0

和你的替代解決方案,而優雅只適用於IE9 +。 爲了安全起見,它會變得更加冗長,這就是爲什麼我更喜歡正則表達式。 – 2014-08-28 11:00:30

+1

[(?=)']的文檔(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)_x(?= y)僅當x是接着是y_。如果你使用[polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill),'.map'也可以在IE8中工作。 – Volune 2014-08-28 11:27:32

0

您不需要使用複雜的正則表達式。 您可以通過空間結合使用劈開Array.filter()方法:

var result = str.split(' ').filter(function(item) { 
    return item.indexOf('.') < 0; 
}); 
+0

謝謝!但我實際上需要這個替換,所以我不得不重建字符串。當然,你不知道,但這就是爲什麼我正在尋找一個正常工作的RegEx。正如我在最後所說的那樣,總是存在着分裂然後走陣列的後備。 – 2014-08-28 10:36:43

+0

@JanPaepke要重建,請使用'.join' – hjpotter92 2014-08-28 10:45:37

+0

我知道,謝謝。 :)正如我所說,我正在試圖找到一個解決方案,而沒有數組繞道。但它似乎是不可能的... – 2014-08-28 10:47:43

1

只需通過參照組索引1

(?:^|)([a-z]+(?= |$)) 

DEMO

> var re = /(?:^|)([a-z]+(?= |$))/g; 
undefined 
> var str = "one two three.four five six.seven eight"; 
undefined 
> var matches = []; 
undefined 
> while (match = re.exec(str)) 
... matches.push(match[1]); 
4 
> console.log(matches); 
[ 'one', 'two', 'five', 'eight' ] 
相關問題