Perl RegExp:存在特定字符串时删除部分字符串

时间:2018-09-05 20:15:36

标签: regex perl

如果字符串包含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;

1 个答案:

答案 0 :(得分: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