正则表达式需要一个url模式

时间:2018-01-08 17:38:24

标签: javascript regex

我正在添加一些简单的路由而不使用任何特定的框架。

当前正则表达式 - >

/^(\w)\/?(\w)\/?(\w)\/?(\d+)$/g

可能的网址格式

settings                                // should be matched to --> group1 = settings, group2 = null, group3 = null, group4 = null
settings/                               // should be matched to --> group1 = settings, group2 = null, group3 = null, group4 = null
settings/205                            // should be matched to --> group1 = settings, group2 = null, group3 = null, group4 = 205

settings/notifications                  // should be matched to --> group1 = settings, group2 = notifications, group3 = null, group4 = null
settings/notifications/                 // should be matched to --> group1 = settings, group2 = notifications, group3 = null, group4 = null
settings/notifications/50               // should be matched to --> group1 = settings, group2 = notifications, group3 = null, group4 = 50

settings/notifications/pingers          // should be matched to --> group1 = settings, group2 = notifications, group3 = pingers, group4 = null
settings/notifications/pingers/         // should be matched to --> group1 = settings, group2 = notifications, group3 = pingers, group4 = null
settings/notifications/pingers/101      // should be matched to --> group1 = settings, group2 = notifications, group3 = pingers, group4 = 101

非常感谢帮助!

2 个答案:

答案 0 :(得分:0)

您可以在string#split/并测试最后一个字是否为数字和空字符串,并使用解构来创建您的对象。



var arr = ['settings', 'settings/','settings/205','settings/notifications','settings/notifications/', 'settings/notifications/50','settings/notifications/pingers','settings/notifications/pingers/','settings/notifications/pingers/101']

var result = arr.map(url => {
  var words = url.split('/');
  var last = null;
  
  if(/\d+/g.test(words[words.length - 1]))
      last = words.pop();
  else if(!words[words.length - 1] || /\s+/g.test(words[words.length - 1]))
    words.pop();
  
  var [group1, group2=null, group3=null] = [...words];
  var group4 = last;
  return {group1, group2, group3, group4};
});

console.log(result);




答案 1 :(得分:0)

请在perl中尝试以下代码。模式本身无处不在。

$string  = "settings/notifications/pingers/101";
#$string  = "settings/notifications/pingers";
#$string  = "settings/notifications";
#$string  = "settings";

$string  =~  m/^(\w+)(?:\/)?(\w+)?(?:\/)?(\w+)?(?:\/)?(\d+)?$/;

print $1."\n"; 
print $2."\n"; 
print $3."\n"; 
print $4."\n";