in reply to combining lists along with a regex
Hello Datz_cozee75,
I'd like the second word of the name to be rendered as only a first initial. I'm completely mystified by the omission of the second letter.
For the input line 2. Kim Washington, do you want the output to be Kim W or K Washington? You say “the second word of the name,” so I’m assuming the former. Here is your regex, with the captures numbered:
my $int = s/^(\d+\.)(\s+)(\w+)(\s+)(\w)(.)/$3$4$5/; # 1 2 3 4 5 6
For the given input line, captures are as follows:
^(2.)( )(Kim)( )(W)(a)shington 1 2 3 4 5 6
The substitution says: match the expression in the left-hand side (regex), then replace the matched part with the right-hand side. The former (i.e., the match) is 2. Kim Wa. The latter (i.e., the replacement) is $3$4$5, which expands to Kim W. This is replaces the matched text within the string, so 2. Kim Wa becomes Kim W and the rest of the string is unaffected. And that’s why the second letter disappears!
For this substitution, I would use a simpler regex (only one capture), like this:
s/^\d+\.\s+(\w+\s+\w).*$/$1/;
For example:
13:08 >perl -wE "my $s = '2. Kim Washington'; $s =~ s/^\d+\.\s+(\w+\s+ +\w).*$/$1/; say $s;" Kim W 13:09 >
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: combining lists along with a regex
by Aldebaran (Curate) on May 09, 2015 at 06:05 UTC | |
by Athanasius (Archbishop) on May 09, 2015 at 08:19 UTC | |
by Aldebaran (Curate) on May 10, 2015 at 01:37 UTC | |
by Athanasius (Archbishop) on May 10, 2015 at 02:54 UTC |