如何为重定向编写正则表达式

时间:2022-02-03 20:46:33

I have some url's

我有一些网址

/a/b?key1=value&key2=value
/a/b/?key1=value&key2=value

I want to redirect them to the url

我想将它们重定向到网址

/a/b/c/?key1=value&key2=value

What i have done till now is i am able to redirect the /a/b/ to /a/b/c using regex

我到目前为止所做的是我能够使用正则表达式将/ a / b /重定向到/ a / b / c

^(\/.*\/)$

also i can not hard code b in the url since it is dynamic and may vary.

我也不能硬编码网址中的b,因为它是动态的,可能会有所不同。

Any help is appreciated.

任何帮助表示赞赏。

1 个解决方案

#1


0  

How about the regex,

正则表达式怎么样

^((?:/[^/?]+){2})/?
  • Replace with $1/c
  • 替换为$ 1 / c

  • /[^/?]+ Matches /, followed by anything other than / or ?.

    / [^ /?] +匹配/,后跟除/或?之外的任何内容。

    The {2} Makes sure that it is repeated twice, once for a and the other for b. This entire match is captured in group 1.

    {2}确保重复两次,一次为a,另一次为b。整个比赛在第1组中捕获。

  • /? Matches an optional / at the end.

    /?最后匹配一个可选/。

Regex Demo

#1


0  

How about the regex,

正则表达式怎么样

^((?:/[^/?]+){2})/?
  • Replace with $1/c
  • 替换为$ 1 / c

  • /[^/?]+ Matches /, followed by anything other than / or ?.

    / [^ /?] +匹配/,后跟除/或?之外的任何内容。

    The {2} Makes sure that it is repeated twice, once for a and the other for b. This entire match is captured in group 1.

    {2}确保重复两次,一次为a,另一次为b。整个比赛在第1组中捕获。

  • /? Matches an optional / at the end.

    /?最后匹配一个可选/。

Regex Demo