Perl RegEx:当存在特定字符串时删除字符串的一部分[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

如果字符串包含PotatoesPeaches,如何应用Perl RegExp删除字符串的第一部分?

如果可能,请不要使用if / else条件,而只使用RegExp。

Input:
Apples Peaches Grapes 
Spinach Tomatoes Carrots
Corn Potatoes Rice

Output:
Peaches Grapes 
Spinach Tomatoes Carrots 
Potatoes Rice

这是我的代码:

#! /usr/bin/perl
use v5.10.0;
use warnings;

$string1 = "Apples Peaches Grapes ";
$string2 = "Spinach Tomatoes Carrots";
$string3 = "Corn Potatoes Rice";

#Use RegExp to output strings with first word deleted  
#if it includes either Peaches or Rice.

$string1 =~ s///;
$string2 =~ s///;
$string2 =~ s///;


say $string1;
say $string2;
say $string3;
regex perl
1个回答
3
投票

您可以使用以下表达式:

^(?=.*\bPeaches\b|.*\bPotatoes\b)\S+\s
  • ^字符串的开头。
  • (?=.*\bPeaches\b|.*\bPotatoes\b)正向前瞻,确保字符串中存在PeachesPotatoes子字符串。
  • \S+\s匹配任何非空白字符,后跟空格。

正则表达式演示here


Perl演示:

use feature qw(say);

$string1 = "Apples Peaches Grapes";
$string2 = "Spinach Tomatoes Carrots";
$string3 = "Corn Potatoes Rice";

$string1 =~ s/^(?=.*\bPeaches\b|.*\bPotatoes\b)\S+\s//;
$string2 =~ s/^(?=.*\bPeaches\b|.*\bPotatoes\b)\S+\s//;
$string2 =~ s/^(?=.*\bPeaches\b|.*\bPotatoes\b)\S+\s//;


say $string1;
say $string2;
say $string3;

打印:

Peaches Grapes
Spinach Tomatoes Carrots
Corn Potatoes Rice
© www.soinside.com 2019 - 2024. All rights reserved.