I have several strings from which I want to extract a substring. Here is an example:
/skukke/integration/build/IO/something
I would like to extract everything after the 3rd / character. In this case, the output should be
/build/IO/something
I tried something like this
/\/\s*([^\\]*)\s*$/
The result of the match is
something
Which is not what I want. Can anyone help?
The regex you can use is:
(?:\/[^\/]+){2}(.*)
See demo
Regex explanation:
(?:\/[^\/]+){2} - Match exactly 2 times / and everything that is not / 1 or more times(.*) - Match 0 or more characters after what we matched before and put into a capturing group 1.Here is a demo on TutorialsPoint:
$str = "/skukke/integration/build/IO/something";
print $str =~ /(?:\/[^\/]+){2}(.*)/;
Output:
/build/IO/something
You can use File::Spec::Functions:
#!/usr/bin/perl
use File::Spec;
$parentPath = "/skukke/integration";
$filePath = "/skukke/integration/build/IO/something";
my $relativePath = File::Spec->abs2rel ($filePath, $parentPath);
print "/". $relativePath;
Outputs /build/IO/something.
See demo on Ideone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With