简体   繁体   English

当具有特定数量的细分时,将正则表达式模式匹配到URL

[英]Matching a regex pattern into an URL when it have a specific number of segments

I have urls like these: 我有这样的网址:

example.com/test/testurl
example.com/test/test-url
example.com/test/testurl/content
example.com/test/test-url/content

I'm working on a redirect in here so, I need a regex to match the url when it has only 2 segments (like the 2 first ones) getting the second segment in a group, but to fail in all the others. 我正在这里进行重定向,因此当它只有2个段(例如前两个2个段)在组中获得第二个段时,我需要一个正则表达式来匹配url,但在所有其他段中都失败。

Here's the pattern I accomplished so far: 到目前为止,这是我完成的模式:

test\/(\w+)(?!\/)\b

This one matches the first url and fails on the third, great. 这个匹配第一个URL,第三个失败,很好。

But it ends up matching the second and fourth url, capturing the word up to the dash. 但最终它与第二个和第四个URL匹配,捕获到破折号的单词。 I'm pulling my hair out on this one, any pointers are appreciated. 我在这上面拉头发,任何指针都值得赞赏。 Thanks in advance ! 提前致谢 ! :) :)

Use this regex instead: 使用此正则表达式代替:

test/([^/]+)

It will capture everything that is not a slash after test/ . test/之后,它将捕获不是斜杠的所有内容。

Escape the slashes appropriately if needed. 如果需要,请适当地转义斜线。

First throw out \\b . 首先抛出\\b That's to match word boundaries and URLs can contain non-word characters. 这是为了匹配单词边界,URL可以包含非单词字符。

I'm going to make the assumption that you're getting the url in its own string without any other accompanying text. 我将假设您在没有任何其他附带文本的情况下以其自己的字符串获取url。

That being the case the following regex will: 在这种情况下,以下正则表达式将:

  • match the start of a string 匹配字符串的开头
  • match one or more characters up to the first forward slash 匹配一个或多个字符,直到第一个正斜杠
  • match /test/ 匹配/测试/
  • match one or more characters up to another slash 将一个或多个字符匹配到另一个斜杠
  • optionally match a slash 可选地匹配斜杠
  • match the end of a string 匹配字符串的结尾

REGEX 正则表达式

^[^/]+/test/[^/]+/?$

REY 雷伊

NO MATCH: example.com/test/
MATCH: example.com/test/testurl
MATCH: example.com/test/test-url
MATCH: example.com/test/test-url/
NO MATCH: example.com/test/testurl/content
NO MATCH: example.com/test/test-url/content

Also if you need to add the protocol, you can rewrite the regex thusly: 另外,如果您需要添加协议,则可以这样重写正则表达式:

^[^:]+://[^/]+/test/[^/]+/?$
^(?=[^\/]*\/[^\/]*\/[^\/]*$).*

Try this. 尝试这个。 This will match only if url has 2 segments. 仅当url有2个段时,此匹配。 See demo. 参见演示。

http://regex101.com/r/gG5fF6/3 http://regex101.com/r/gG5fF6/3

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

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