简体   繁体   English

根据正则表达式模式分割字符串

[英]Split the string based on regex pattern

I am new to using regular expression. 我是使用正则表达式的新手。 Given the string, I am trying to achieve the following: 给定字符串,我正在尝试实现以下目标:

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

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

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

In both cases, i would like to find the last string delimited by '/' 在这两种情况下,我都想找到以'/'分隔的最后一个字符串

ie, '/' like %s\\/%s . '/'就像%s\\/%s delimiter '/' having strings on both sides 分隔符'/' ,两边都有字符串

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

I tried different patterns using regex, but it incorrectly returns 'str4' delimited by '//' . 我使用正则表达式尝试了不同的模式,但是错误地返回了以'//'分隔的'//' 'str4' '//'

How do I avoid this? 如何避免这种情况?

Thanks 谢谢

Instead of using String.prototype.split() , try to use String.prototype.match() to directly target what you need: 不要使用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 */ 

Less straight forward, you can also use a replacement strategy with String.prototype.replace() . 不太直接的是,您还可以使用String.prototype.replace()的替换策略。 The idea is to remove all until the last slash not preceded and not followed by an other slash: 这个想法是删除所有内容,直到最后一个斜杠没有出现在前面,也没有后面的其他斜杠为止:

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

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

You could use a regex like this: 您可以使用以下正则表达式:

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

Working demo 工作演示

And grab the content from capturing group 并从捕获组中获取内容

I think you can resolve this considering using arrays too! 我认为您也可以考虑使用数组来解决此问题!

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 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM