in reply to reg expression question
Hello healingtao, and welcome to the Monastery!
To begin, I would split the string on its first sequence of one or more whitespace characters. Only then would I apply a regular expression to the right-hand side of the split:
#! perl use strict; use warnings; use Test::More; my %data = ( 'GNRABS 2014-186' => 'GNRABS14-186', 'A10 2013-1' => 'A1013-1', 'CGBAM 2014-HD' => 'CGBAM14-HD', 'FHMS K032' => 'FHMS-K032', ); is(rewrite($_), $data{$_}) for keys %data; done_testing(); sub rewrite { my ($string) = @_; my ($left, $right) = split /\s+/, $string, 2; if (my @m = $right =~ /\d{2}(\d{2})(.*)/) { $right = $m[0] . ($m[1] =~ /^-/ ? '' : '-') . $m[1]; } else { $right = '-' . $right unless $right =~ /^-/; } return $left . $right; }
See also perlretut.
Hope that helps,
Update: Improved wording.
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: reg expression question
by healingtao (Novice) on Jan 29, 2015 at 07:14 UTC | |
by Athanasius (Archbishop) on Jan 29, 2015 at 08:02 UTC | |
by Anonymous Monk on Jan 29, 2015 at 08:06 UTC | |
by Athanasius (Archbishop) on Jan 29, 2015 at 08:42 UTC | |
by AnomalousMonk (Archbishop) on Jan 29, 2015 at 11:14 UTC | |
|