简体   繁体   中英

select particular part of a url using Regex

Say I have a url like /dir/name.json and I want to select and return anything which is between /dir/ and .json , in this case name . So I came up with something like this:

> var url = "/dir/name.json";
> var pattern = /\/\w+\./
> url.match(pattern) 
[ '/name.', index: 4, input: '/dir/name.json' ]

but I just want to match name and not /name.

Of course there is another way to do this by using substr :

> var url = "/dir/name.json";
> url.substr(5, url.length-10)
'name'

but I wonder if I can do this using Regex

Assuming the dot is the discriminant (so it cannot be present in dir names...)

x = (/\w+(?=\.)/).exec("/dir/name.json")

could do it.

The syntax (?=...) describes a sub-expression that must match but that is not considered "consuming characters" so the meaning of the whole regexp is "a non-empty sequence of word characters followed by a dot (not considering it part of the match)".

The technical name is "positive look-ahead zero-width assertion".

If the dot could be present in directory names something that could work is:

x = (/\w+(?=\.\w*$)/).exec("/dir.1/dir.2/name.json")

because the lookahead now wants to be sure that after the dots there are only word characters (if any) and then the string ends.

Finally, if the extension could be missing completely:

x = (/\w+(?=\.\w*$|$)/).exec("/dir.1/dir.2/name.json")

works also for "dir.1/dir.2/name" .

Try this:

 alert("/dir/name.json".match(/\\/(\\w+)\\./)[1]) alert("/dir/name.json".split("/").pop().split(".").shift()) 

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