2017-03-20 38 views
0

我是新來使用正則表達式。鑑於串,我想實現以下目標:基於正則表達式分割字符串

actStr1 = 'st1/str2/str3' 
expStr1 = 'str3' 

actStr2 = 'str1/str2/str3 // str4' 
expStr2 = 'str3 // str4' 

actStr3 = 'a1/b1/c1 : c2' 
expStr3 = 'c1 : c2' 

在這兩種情況下,我想找到'/'

即,'/'分隔像%s\/%s最後一個字符串。雙方

result1 = 'str3 // str4' 
result2 = 'str3' 

分隔符'/'有字符串我嘗試使用正則表達式不同的模式,但它錯誤地返回'str4'通過'//'分隔。

我該如何避免這種情況?

感謝

+1

http://stackoverflow.com/editing-help –

+0

添加你試過 – binariedMe

+0

的正則表達式我認爲你需要表現出一些真正的樣本串,你的正則表達式,並預期result.Otherwise閱讀有些困惑。 –

回答

1

而不是使用String.prototype.split(),儘量使用String.prototype.match()直接定位你需要的東西:

var testStrings = [ 'str1/str2/str3', 
 
        'str1/str2/str3 // str4', 
 
        'a1/b1/c1 : c2' ]; 
 

 
var re = new RegExp('[^/]*(?://+[^/]*)*$'); 
 

 
testStrings.forEach(function(elt) { 
 
    console.log(elt.match(re)[0]); 
 
}); 
 
/* str3 
 
    str3 // str4 
 
    c1 : c2 */

沒那麼直接,你也可以使用一個替代戰略, String.prototype.replace()。這樣做是爲了消除所有,直到最後一個斜線之前沒有和後面沒有一個其他的斜線:

var re = new RegExp('(?:.*[^/]|^)/(?!/)'); 

testStrings.forEach(function(elt) { 
    console.log(elt.replace(re, '')); 
}); 
+1

謝謝@revo,但似乎這個功能不返回良好的數組(匹配的索引和輸入字符串丟失)。但在未來我會嘗試使用這個功能。 –

0

你可以使用這樣的正則表達式:

\/(\w+(?:$| .*)) 

Working demo

而且抓取捕獲組的內容

0

我想你可以使用數組來解決這個問題了!

function lastSlug(str) { 
    // remove the '//' from the string 
    var b = str.replace('//', ''); 
    // find the last index of '/' 
    var c = b.lastIndexOf('/') + 1; 
    // return anything after that '/' 
    var d = str.slice(c); 
    return d; 
} 

Demo

相關問題