Sanket Sanket - 24 days ago 7
Perl Question

How can I get the word preceding the last occurrence of a substring?

I am trying to get the required word by applying a regex pattern to the whole string.

Here is my string:

Birla Sun Life Global Real Estate Fund - Retail Plan - Direct Plan - Growth Option

SBI GOLD FUND - DIRECT PLAN - DIVIDEND


I want to get
Plan
type which is
Direct


Sometimes
Plan
appears once and sometimes twice, so the pattern must work for both cases.

Here is what I have written so far:

$pname = 'Birla Sun Life Global Real Estate Fund - Retail Plan - Direct Plan - Growth Option';

if ( $pname =~ / ([^\s]*) plan(?!^plan$)*/ig ) # regex to get plan type
{
$plan_type = $1;
}
print "$1";


But it gives the output
Retail
instead of
Direct
.

What should I do so that I can get
Direct
as the
Plan
type?

Answer

Try this:

(\w+)\s+Plan(?!.*Plan)

Explanation

Run the perl code here

use strict;

my $str = 'Birla Sun Life Global Real Estate Fund - Retail Plan - Direct Plan - Growth Option\';  ';
my $regex = qr/(\w+)\s+Plan(?!.*Plan)/p;

if ( $str =~ /$regex/g ) {
  print "$1";
}
Comments