I just cant seem to be able to figure out how to match the following
in the string /hello/there-my-friend
I need to capture everything after the last /
and before the last -
So it should capture there-my
.
I just cant seem to be able to figure out how to match the following
in the string /hello/there-my-friend
I need to capture everything after the last /
and before the last -
So it should capture there-my
.
Here's the Regular Expression you're looking for:
#(?<=/)[^/]+(?=-[^-/]*$)#
I'll break it down in a minute, but there are probably better ways to do this.
I might do something like this:
$str = "/hello/there-my-friend";
$pieces = explode('/', $str);
$afterLastSlash = $pieces[count($pieces)-1];
$dashes = explode('-', $afterLastSlash);
unset($dashes[count($dashes)-1]);
$result = implode('-', $dashes);
The performance here is guaranteed linear (limiting factor being the length of $str plus the length of $afterLastSlash. The regular expression is going to be much slower (as much as polynomial time, I think - it can get a little dicey with lookarounds.)
The code above could easily be pared down, but the naming makes it more clear. Here it is as a one liner:
$result = implode('-', array_slice(explode('-', array_slice(explode('/', $str), -1)), 0, -1));
But gross, don't do that. Find a middle ground.
As promised, a breakdown of the regular expression:
#
(?<= Look behind an ensure there's a...
/ Literal forward slash.
) Okay, done looking behind.
[^/] Match any character that's not a forward slash
+ ...One ore more times.
(?= Now look ahead, and ensure there's...
- a hyphen.
[^-/] followed by any non-hyphen, non-forward slash character
* zero or more times
$ until the end of the string.
) Okay, done looking ahead.
#
^".*/([^/-]*)-[^/-]*$
Syntax may vary depending on which flavor of RE you are using.
Try this short regex :
/\K\w+-\w+
Your regex engine need \K
support
or
(?<=/)\w+-\w+
(more portable)
\K
is close to (?<=/)
: a look-around regex advanced technique\w
is the same as [a-zA-Z0-9_]
, feel free to adapt itThis is not an exact answer to your question (its not a regex), but if you are using C# you might use this:
string str = "/hello/there-my-friend";
int lastSlashIndex = str.LastIndexOf('/');
int lastDashIndex = str.LastIndexOf('-');
return str.Substring(lastSlashIndex, lastDashIndex - lastSlashIndex);
This will do it:
(?!.*?/).*(?=-)
Depending on your language, you might need to escape the /
Breakdown:
1. (?!.*?/) - Negative look ahead. It will start collecting characters after the last `/`
2. .* - Looks for all characters
3. (?=-) - Positive look ahead. It means step 2 should only go up to the last `-`
Edited after comment: No longer includes the /
and the last -
in the results.