【问题标题】:How to get last part from the URL with regular expression? [duplicate]如何使用正则表达式从 URL 中获取最后一部分? [复制]
【发布时间】:2019-05-23 10:05:57
【问题描述】:

enter code here 我有以下网址(部分)。其中我需要获取详细信息 在最后的“/”之后

/magasins/vos-magasins/le-bhv-marais
/magasins/vos-magasins/le-bhv-marais-homme
/magasins/vos-magasins/bhv-marais-parly2
/magasins/le-bhv-marais-la-niche
/magasins/vos-magasins/mobicity-au-bhv-marais
/magasins/vos-magasins/gucci-au-bhv-marais

我知道如何匹配所有部分如下

/magasins/[a-z-]+/?[a-z0-9-]+

但我需要在最后的“/”之后得到最后一部分。

【问题讨论】:

  • 试试“斜线和任何单词”/\/[\w-]+$/?
  • 你必须使用正则表达式吗?这可以在不使用的情况下更轻松地完成。
  • var arr = url.split('/'); console.log(arr[arr.length-1]);
  • @Quentin,以前的答案没有为我提供正确的解决方案。可能是问题标题相同但内容不同!

标签: javascript regex


【解决方案1】:

这个正则表达式会为你工作:

(?<=\/)[a-z0-9-]+?$

正则表达式demo

解释:

(?&lt;= )lookbehind 找到一个模式来开始你的匹配(但不会将它包含在你的匹配组中)。

\/ 匹配文字 /

[a-z0-9-] 匹配字母数字字符或连字符-

+?该字符必须出现一次或多次,直到下一个模式

$ 输入结束

由于不是所有浏览器都支持lookbehind,所以我也为javascript提供了这个版本:

var regex = /\/([a-z0-9-]+)$/

match = "/magasins/vos-magasins/le-bhv-marais".match(regex); 
console.log(match[1]); // le-bhv-marais

match = "/magasins/vos-magasins/le-bhv-marais-homme".match(regex);
console.log(match[1]); // le-bhv-marais-homme

match = "/magasins/vos-magasins/bhv-marais-parly2".match(regex);
console.log(match[1]); // bhv-marais-parly2

match = "/magasins/le-bhv-marais-la-niche".match(regex);
console.log(match[1]); // le-bhv-marais-la-niche

match = "/magasins/vos-magasins/mobicity-au-bhv-marais".match(regex);
console.log(match[1]); // mobicity-au-bhv-marais

match = "/magasins/vos-magasins/gucci-au-bhv-marais".match(regex);
console.log(match[1]); // gucci-au-bhv-marais

【讨论】:

  • 这里“?”表示 + 的可选
  • 当添加到+ 时,+? 表示一次或多次但 lazy 匹配,这意味着它将尽可能少地重复,同时保持真实。没有?,单独的+greedy,这意味着它会尽可能多地重复。在此示例中,它可能没有什么区别,您可以放心地省略 ?
  • 我还更新了答案以适用于大多数浏览器(不需要后视)
  • @user 不客气!
猜你喜欢
  • 1970-01-01
  • 2015-02-22
  • 2015-02-20
  • 2018-08-18
  • 2016-08-05
  • 2012-02-06
  • 1970-01-01
  • 2010-09-06
  • 2014-09-04
相关资源
最近更新 更多