Perl regex matches substring

I have some lines 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 third character /. In this case, the output should be

/build/IO/something

I tried something like this

/\/\s*([^\\]*)\s*$/

Match result

something

This is not what I want. Can anyone help?

+4
source share
2 answers

Regular decision

The regular expression you can use is the following:

(?:\/[^\/]+){2}(.*)

Watch the 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 earlier and put in capture group 1.

TutorialsPoint:

$str = "/skukke/integration/build/IO/something";
print $str =~ /(?:\/[^\/]+){2}(.*)/;

:

/build/IO/something

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;

/build/IO/something.

. Ideone

+2

:

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

, .

0

All Articles