如何获取子字符串最后一次出现之前的单词?

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

我试图通过对整个字符串应用正则表达式模式来获取所需的词。

这是我的字符串:

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

SBI GOLD FUND - DIRECT PLAN - DIVIDEND

我想获得 Plan 类型,即 Direct

有时 Plan 出现一次,有时出现两次,因此该模式必须适用于这两种情况。

以下是我到目前为止所写的内容:

$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 = ;
}
print "";

但它给出了输出 Retail 而不是 Direct

我应该怎么做才能得到 Direct 作为 Plan 类型?

试试这个:

(\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 "";
}

我认为你的做法是错误的。魔术正则表达式 (IMO) 很少是解决问题的正确方法。

为什么不呢,试试 split 分隔符上的字段 (-):

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

my ( $fund, $something, $type, $option ) = split /\s*-\s*/, $str;
print $type,"\n";

要获取字符串中任何内容的最后次出现,您可以使用尽可能多的字符串匹配来启动正则表达式模式

这是一个使用您自己的数据的解决方案。请注意,您的全局 /g 修饰符充其量是多余的,而且确实没有意义

我还添加了 /x 修饰符,它允许我向模式添加无关紧要的白色 space 以使其更具可读性。除了最琐碎的模式外,它对所有模式都有用

use strict;
use warnings 'all';

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

if ( $pname =~ / .* \b (\w+) \s+ plan \b /ix ) {
    $plan_type = ;
}

print $plan_type // 'undef', "\n";

输出

 Direct