简体   繁体   English

正则表达式以匹配URL-字符串末尾的数字,但也匹配字符串开头的字符

[英]Regex to match URL - number at end of string, but also match characters at start of string

I need to match the following URL format 我需要匹配以下网址格式

/yc/leroy-jenkins-123

So I need to match both the /yc/ part and the 123 所以我需要同时匹配/yc/部分和123

I am able to match the URL when its /leroy-jenkins-123 with the following 我可以将URL的/leroy-jenkins-123与以下内容匹配

server.get(/([^-]*)$/, (req, res) => {
    const actualPage = '/profile'
    const queryParams = { id: req.params[0] }
    app.render(req, res, actualPage, queryParams)
})

So I can match the 123 with ([^-]+)$ but how do I match the /yc/ part too? 所以我可以将123([^-]+)$匹配,但是我也如何匹配/yc/部分?

You can use this regex to and capture the values from group1 and group2, 您可以使用此正则表达式捕获并捕获来自group1和group2的值,

^(\/[^\/]+\/).*?(\d+)$

Regex Demo 正则表达式演示

Explanation: 说明:

  • ^ - Matches start of string ^ -匹配字符串的开头
  • (\\/[^\\/]+\\/) - Matches a / followed by any character other than / one or more further followed by a / and captures this value in group1 (\\/[^\\/]+\\/) -匹配一个/随后以外的任何字符/一个或多个其它随后是/和在组1捕捉该值
  • .*? - Allows optional matching of zero or more any characters -允许零个或多个任意字符的可选匹配
  • (\\d+)$ - Matches one or more digits and captures it in group2 followed by end of string (\\d+)$ -匹配一个或多个数字并在组2中捕获它,然后在字符串末尾捕获

Just alternate with ^\\/\\w+\\/ : 只需与^\\/\\w+\\/交替:

server.get(/([^-]+)$|^\/\w+\//, ...

Also note that you should probably repeat at least one non-dash character before the end of the string, else it can match the empty string at the end, eg, a URL of 另请注意,您可能应该在字符串末尾重复至少一个非破折号,否则它可以与末尾的空字符串匹配,例如URL为

/

and nothing else would match, because there are (at least) zero non-dash characters at the end of the string, which may well not be desirable. 并且没有其他匹配项,因为字符串末尾(至少)有零个非破折号字符,这可能是不希望的。

Unless the group is actually being used for something, feel free to leave it off entirely: 除非该小组实际用于某件事,否则请随意将其完全抛弃:

server.get(/[^-]+$|^\/\w+\//, ...

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

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