I have the following URL:
And I need to get the text that is after v1/
and before /
(between the slashes), in this case the word entity
. I'm using the following regex, but what I get back is entity/1231
on group 1:
/^[^\#\?]+\/v1\/([^\?]+).*$/
Any idea on how to get rid of 1231
or anything that es after entity
?
I have the following URL:
http://data.test./api/v1/entity/1231
And I need to get the text that is after v1/
and before /
(between the slashes), in this case the word entity
. I'm using the following regex, but what I get back is entity/1231
on group 1:
/^[^\#\?]+\/v1\/([^\?]+).*$/
Any idea on how to get rid of 1231
or anything that es after entity
?
-
1
v1\/([^/]+)
orv1\/(.*?)\/
– Tushar Commented Mar 29, 2017 at 16:27 -
If the parts are fixed
"http://data.test./api/v1/entity/1231".split("/")[5]
– Alex K. Commented Mar 29, 2017 at 16:27 -
If the URLs you're working with are that predictable then regular expressions, while possible, may be an overly-plex tool for the job. Are the URLs changeable? Will it always be "after
v1/
and before [the next]/
"? – David Thomas Commented Mar 29, 2017 at 16:28 - @DavidThomas Yes, they are predictable – arielcr Commented Mar 29, 2017 at 16:33
-
You need
str.match(/\/v1\/([^\/]+)/)[1]
– Wiktor Stribiżew Commented Mar 29, 2017 at 16:33
2 Answers
Reset to default 6You may capture the value you need into a capturing group with new RegExp("/v1/([^/]+)"
:
var str = "http://data.test./api/v1/entity/1231";
var res = str.match(new RegExp("/v1/([^/]+)"));
if (res)
console.log(res[1]);
The /v1/([^/]+)
matches:
/v1/
- a literal string/v1/
([^/]+)
- capturing group 1 matching one or more chars other than/
.
Thanks to the constructor notation in the RegExp definition, there is no need to escape forward slashes in the regex pattern.
Alternatively, since ECMAScript 2018 enabled lookbehind usage in the JavaScript RegExp patterns, you can also use a lookbehind-based approach to get the value you need directly as a whole match:
const str = "http://data.test./api/v1/entity/1231";
const res = str.match(/(?<=\/v1\/)[^\/]+/);
if (res) {
console.log(res[0]);
}
Details:
(?<=\/v1\/)
- a positive lookbehind that matches a location that is immediately preceded with/v1/
text[^\/]+
- one or more chars other than a/
char.
try this:
^[^\#\?]+\/v1\/([^\?]+).*(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/1231)$
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745385889a4625437.html
评论列表(0条)