【问题标题】:How can I get the word preceding the last occurrence of a substring?如何获取最后一次出现子字符串之前的单词?
【发布时间】:2016-11-10 05:53:14
【问题描述】:

我正在尝试通过将正则表达式模式应用于整个字符串来获取所需的单词。

这是我的字符串:

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

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

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

【问题讨论】:

  • Plan type which is Direct”是什么意思?您需要字符串中的哪些特定短语或单词?
  • 您是否要在最后一次出现 Plan 之前获取单词?
  • 你试过regex101.com吗?

标签: regex perl regex-negation


【解决方案1】:

我认为你的做法是错误的。神奇的正则表达式(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";

【讨论】:

  • 我不太确定总是有四个字段!
【解决方案2】:

试试这个:

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

【讨论】:

  • 感谢您的回复,但这对我不起作用,因为这里我举了一个例子,但我还有一些其他字符串,其中 Plan 是单次的,所以我需要 reg-ex 给就在计划之前的字符串,但计划应该在整个单词的右侧,请再次查看我编辑的问题....
  • 您需要更好地解释业务,其他任何人都无法帮助您...您想要在计划最后一次出现之前的文字吗?
  • 是的,正是我需要在最后一次出现计划之前的文本
  • @Sanket 现在再试一次
  • @Sanket:您尚未接受任何问题的答案。请参阅meta.stackexchange.com/questions/5234/…
【解决方案3】:

要获得字符串中任何内容的最后次出现,您可以使用贪婪匹配开始正则表达式模式,该匹配会尽可能多地消耗字符串

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

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

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

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

输出

 Direct

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多