簡體   English   中英

根據正則表達式模式分割字符串

[英]Split the string based on regex pattern

我是使用正則表達式的新手。 給定字符串,我正在嘗試實現以下目標:

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' '//'

如何避免這種情況?

謝謝

不要使用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, ''));
});

您可以使用以下正則表達式:

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

工作演示

並從捕獲組中獲取內容

我認為您也可以考慮使用數組來解決此問題!

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;
}

演示版

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM