我有来自亚马逊的乔治迈克尔的DVD曲目列表的剪切和粘贴$str以及随后的代码,通过分割前两位数字和其余数字来处理它:
$str = "20 Fastlove 21 Jesus To A Child 22 Spinning the Wheel 23 Older 24 Outside 25 As (with Mary J. Blige) 26 Freeek! 27 Amazing 28 John and Elvis are Dead 29 Flawless (Go To The City) 30 Shoot The Dog 31 Roxanne 32 An Easier Affair 33 If I Told You That (with Whitney Houston) 34 Waltz Away Dreaming 35 Somebody To Love 36 I Can’t Make You Love Me 37 Star People '97 38 You Have Been Loved 39 Killer/ Papa Was A RollIn Stone 40 Round Here";
while ($str =~ /(\d{2}) (\S+)/g) {
print "$1 $2\n";
}
Run Code Online (Sandbox Code Playgroud)
结果:
20 Fastlove
21 Jesus
22 Spinning
23 Older
24 Outside
25 As
26 Freeek!
27 Amazing
28 John
29 Flawless
30 Shoot
31 Roxanne
32 An
33 If
34 Waltz
35 Somebody
36 I
37 Star
97 38
39 Killer/
40 Round
Run Code Online (Sandbox Code Playgroud)
以上类型的作品,但不包括完整的曲目名称.关于如何获得我想要的结果的任何建议?我期待或想要的结果是:
20 Fastlove
21 Jesus To A Child
22 Spinning the Wheel
[etc.]
Run Code Online (Sandbox Code Playgroud)
正如Ignacio所说,这不能真正以100%的准确度完成,因为曲目名称可以包含数字.但是既然你可以假设曲目编号是连续的,你可以接近100%:
my $str = "20 Fastlove 21 Jesus To A Child 22 Spinning the Wheel 23 Older 24 Outside 25 As (with Mary J. Blige) 26 Freeek! 27 Amazing 28 John and Elvis are Dead 29 Flawless (Go To The City) 30 Shoot The Dog 31 Roxanne 32 An Easier Affair 33 If I Told You That (with Whitney Houston) 34 Waltz Away Dreaming 35 Somebody To Love 36 I Cant Make You Love Me 37 Star People '97 38 You Have Been Loved 39 Killer/ Papa Was A RollIn Stone 40 Round Here";
my ($track) = ($str =~ /^(\d+)/) or die "No initial track number";
my $next;
while ($next = $track + 1 and
$str =~ s/^\s* # optional initial whitespace
$track \s+ # track number followed by whitespace
(\S.*?) # title begins with non-whitespace
(?= \s+ $next \s # title stops at next track #
| $ ) # or end-of-string
//x) {
print "$track $1\n";
$track = $next;
}
die "$str left over" if $str =~ /\S/; # sanity check
Run Code Online (Sandbox Code Playgroud)
这会修改$str,因此如有必要,请复制.
如果曲目的标题包含下一曲目编号,则会失败,但这应该是相当不常见的.如果缺少曲目或者曲目编号不连续,它也将失败.