首页 > 解决方案 > 正则表达式删除字符串的前导部分

问题描述

我有不同的字符串,但格式相同,三个单词用空格分隔。目标是删除字符串的第一部分。换句话说,删除每个字符串的前导数据。

什么 Perl 正则表达式可以让我删除前导数据,同时保持字符串的其余部分不受影响?

输入

String 1: Apples Peaches Grapes
String 2: Spinach Tomatoes Carrots
String 3: Corn Potatoes Rice

输出

String 1: Peaches Grapes
String 2: Tomatoes Carrots
String 3: Potatoes Rice

Perl

#! /usr/bin/perl

use v5.10.0;
use warnings;

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

# Apply ReqExp to Delete the First Part of the String
$string1 =~ s/.../; 

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

标签: regexperl

解决方案


$string1 =~ s/^\S+\h+//; 
  • ^字符串的开头
  • \S+1 个或多个非空格字符
  • \h+1个或多个水平空间

如果您使用的是低于 v5.10 的 Perl 版本,您可以使用:

$string1 =~ s/^\S+[ \t]+//; 

推荐阅读