开发者

Regular Expression for "infinite" URL

开发者 https://www.devze.com 2023-04-02 00:24 出处:网络
I am trying to create a match for this pattern: /page/some/thing/is/written/here where /page is will always match a-zA-Z0-9 and everything after /page can containt the characters a-zA-Z0-9-/

I am trying to create a match for this pattern:

/page/some/thing/is/written/here

where /page is will always match a-zA-Z0-9 and everything after /page can containt the characters a-zA-Z0-9-/ My idea is that "page" always is the page which the user will see, and the rest are parameters, separated by / (p1/p2/p3) etc.

This is what I have come up with: ^([a-zA-Z]+)/([A-Za-z0-9-开发者_运维百科/]+)$ It works until 3 slashes: page/is/nice

But if I add another parameter like this: page/is/nice/crash It crashes.

Any suggestions? Thanks.


Try this:

^/?[a-zA-Z]+(/[A-Za-z0-9]+)*$

Broken down:

  • ^ - lead anchor
  • /? - it might start with a slash
  • [a-zA-Z]+ - one or more letters
  • (/[A-Za-z0-9]+)* - zero or more /alphanumerics (with at least one alphanumeric)
  • $ - end anchor

If you have no need to capture the ending, you should use non-capturing groups instead:

^/?[a-zA-Z]+(?:/[A-Za-z0-9]+)*$    

If you want an optional slash at the end, try this:

^/?[a-zA-Z]+(?:/[A-Za-z0-9]+)*/?$

Note: You might have to delimit the slashes depending on your programming language.

0

精彩评论

暂无评论...
验证码 换一张
取 消