Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl regular expression match substring

Tags:

regex

perl

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?

like image 565
swaroop kukke Avatar asked Oct 31 '22 04:10

swaroop kukke


1 Answers

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

like image 52
Wiktor Stribiżew Avatar answered Nov 15 '22 12:11

Wiktor Stribiżew