• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 372
  • Last Modified:

Perl Regular expression needed

I have a path variable. It always starts with R:\\ and is followed by one or more directories beneath. I need a regular expression that keeps the 1st folder and removes the drive ( R:\\ ) and anything that follows the first folder. So all that will be left is the first folder name. Have a couple examples below to make it clear what I'm wanting.

Example 1
$file = R:\\SomeDirectory123\\BlaBlaBla\\Hello123\\
$folder =~ EXPRESSIONHERE that modifies $file;

Value of $folder should be: SomeDirectory123

Example 2
$file = R:\\SomeOtherDirectory321\\
$folder =~ EXPRESSIONHERE that modifies $file;

Value of $folder should be: SomeOtherDirectory321
  • 2
2 Solutions
my $file = 'R:\\SomeDirectory123\\BlaBlaBla\\Hello123\\';
my ($folder) = ($file =~ /\\(.*?)\\/);
print "F $folder\n";

Open in new window

The comment by parparov is probably workable, but I would feel slightly safer anchoring the regex to the left hand end to avoid picking up the wrong directory: (And carrying out using two lines to be easier self-documenting:

$file =~ m/^R:\\(.*?)\\/;
$folder = $1;


The solution by roundel35 is indeed safest and securest if you wish to restrict everything to drive R:; it will fail if the drive letter changes. The minimal matching ensures the left-side anchoring and will get the top directory on a local drive or a network share.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now