5

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 3
    It sounds like what you *really* want to do is to create file paths relative to `/skukke/integration`. You should avoid pattern matching and use the [`File::Spec::Functions`](https://metacpan.org/pod/File::Spec::Functions) module and the `abs2rel` function. But you need to explain better what it is that you need before anyone can write a solution – Borodin May 10 '15 at 16:25

2 Answers2

2

Regex Solution

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

Non-regex solution

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    @Downvoter: https://goo.gl/YX5KQr is for you. Downvoting working solutions is BAD. – Wiktor Stribiżew May 10 '15 at 16:39
  • sorry for asking, what is the purpose of ?: at the beginning of the regex? – lightbringer May 11 '15 at 06:37
  • The `(?:...)` is a [non-capturing group](http://stackoverflow.com/questions/3512471/non-capturing-group) to make matching less resource-consuming. Anyway, we are not using that value. If you need it, add round brackets (a [capturing group](http://www.regular-expressions.info/brackets.html)) around the whole beginning part: `((?:\/[^\/]+){2})(.*)`. – Wiktor Stribiżew May 11 '15 at 06:48
0

Use This Regex:

my $string = "/skukke/integration/build/IO/something";
$string =~ s/\/[a-zA-Z0-9]*\/[a-zA-Z0-9]*//;

Hope This helps.

AbhiNickz
  • 1,035
  • 2
  • 14
  • 32