简体   繁体   中英

Regex to get a specific part of an URL

Say I've got an URL:

http://www.example.com/foo/bar/yes_no_no.html

I'm looking for a regex that can extract all the characters of the filename up to the first underscore. So in the above URL I want to extract "yes".

So far I managed to get the whole "yes_no_no" bit using:

/([^\\/]+)(?=\\.\\w+$)/ , but I can't seem to get it to only match "yes".

Try this:

/\/([^_\/]+)_?[^\/]*\.[a-z]+$/

Example:

 console.log('http://www.example.com/foo/bar/yes_no_no.html'.match(/\\/([^_\\/]+)_?[^\\/]*\\.[az]+$/)[1]) console.log('http://www.example.com/foo/bar/yes.html'.match(/\\/([^_\\/]+)_?[^\\/]*\\.[az]+$/)[1]) 

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