简体   繁体   中英

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

I am able to match the URL when its /leroy-jenkins-123 with the following

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?

You can use this regex to and capture the values from group1 and 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
  • .*? - 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

Just alternate with ^\\/\\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

/

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+\//, ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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