• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 369
  • 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
0
KGNickl
Asked:
KGNickl
  • 2
2 Solutions
 
parparovCommented:
my $file = 'R:\\SomeDirectory123\\BlaBlaBla\\Hello123\\';
my ($folder) = ($file =~ /\\(.*?)\\/);
print "F $folder\n";

Open in new window

0
 
roundel35Commented:
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;

Regards,

John
0
 
parparovCommented:
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.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

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