سؤال

I need to extract a substring from a given string in my perl program. The string is of the form:

<PrefixString>_<MyString>_<SuffixString>.pdf

Example: abcd_ThisIsWhatIWant_xyz.pdf

I need to extract "ThisIsWhatIWant"

Can anyone help me please?

Thanks!

This is what I am trying through a subroutine:

sub extractString{
        my ($fileName) = @_;
        my $offset = 2;
        my $delimeter = '_';
        my $fileNameLen = index($fileName, $delimeter, $offset);
        my $extractedFileName = substr($fileName, 8, $fileNameLen-1);
        return $extractedFileName;
  }
هل كانت مفيدة؟

المحلول

You can either use split or a regular expression. This short program shows both alternatives.

use strict;
use warnings;

my $filename = 'abcd_ThisIsWhatIWant_xyz.pdf';

my ($substring1) = $filename =~ /_([^_]*)_/;
print $substring1, "\n";

my $substring2 = (split /_/, $filename)[1];
print $substring2, "\n";

output

ThisIsWhatIWant
ThisIsWhatIWant
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top