Reputation: 53
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?
Upvotes: 5
Views: 1270
Reputation: 1113
Use This Regex:
my $string = "/skukke/integration/build/IO/something";
$string =~ s/\/[a-zA-Z0-9]*\/[a-zA-Z0-9]*//;
Hope This helps.
Upvotes: 0
Reputation: 627507
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
Upvotes: 2