如何使用正则表达式在url中获取路径

时间:2018-05-25 11:34:35

标签: javascript regex

我对正则表达式不是很好

我想要一个匹配这些的正则表达式:

http://localhost:3000/categories/football
http://localhost:3000/categories/football/2222/45444
http://localhost:3000/categories/tennis/45454
http://localhost:3000/categories/football/12
http://localhost:3000/categories/cricket/

基本上,对于以上所有可能的网址路径,我希望返回categories/之后和第二个/之前的字词

足球,足球,网球,足球,板球

我到目前为止: (categories)/\w+

但很明显,这仍然包括类别

5 个答案:

答案 0 :(得分:2)

您可以将捕获组从(categories)更改为(\w+)并使用正向前瞻(?=来断言后面的内容是可选的(?=\/?)正斜杠。

您要查找的值位于捕获的第1组中。

categories\/(\w+)(?=\/?)

const strings = [
  "http://localhost:3000/categories/football",
  "http://localhost:3000/categories/football/2222/45444",
  "http://localhost:3000/categories/tennis/45454",
  "http://localhost:3000/categories/football/12",
  "http://localhost:3000/categories/cricket/"
];
let pattern = /categories\/(\w+)(?=\/?)/;

strings.forEach((s) => {
  console.log(s.match(pattern)[1]);
});

答案 1 :(得分:2)

为什么不拆分 - 如果类别是路径名中的第二个

var loc = "/categories/football/2222/45444"; // var loc = location.pathname
console.log(loc.split("/")[2])

答案 2 :(得分:1)

你走了。



var url1 = "http://localhost:3000/categories/football"
var url2 = "http://localhost:3000/categories/football/2222/45444"
var url3 = "http://localhost:3000/categories/tennis/45454"
var url4 = "http://localhost:3000/categories/football/12"
var url5 = "http://localhost:3000/categories/cricket/"

var regex = /categories\/(\w+)(?=\/?)/;
console.log(regex.exec(url1)[1]);
console.log(regex.exec(url2)[1]);
console.log(regex.exec(url3)[1]);
console.log(regex.exec(url4)[1]);
console.log(regex.exec(url5)[1]);




答案 3 :(得分:0)

您可以使用RegEx (?<=categories\/)[^\/\n]+

  • (?<=categories\/)确保您的匹配前面有categories/

  • [^\/\n]+只匹配/newline 1次或以上的任何内容

Demo at Regex101.

var re =  /(?<=categories\/)[^\/\n]+/
console.log(
"http://localhost:3000/categories/football/2222/45444".match(re)[0]
)

答案 4 :(得分:0)

您可以从捕获组中排除类别

let regex = /(?:categories)+(\/\w+)/;
urls.forEach((str) => {
  console.log(str.match(regex)[1].replace('/',''));
});