如果字符串包含Potatoes
或Peaches
,如何应用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;
答案 0 :(得分:3)
您可以使用以下表达式:
^(?=.*\bPeaches\b|.*\bPotatoes\b)\S+\s
^
字符串的开头。(?=.*\bPeaches\b|.*\bPotatoes\b)
正向查找,确保字符串中存在Peaches
或Potatoes
子字符串。\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