Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Hello, I have a set of strings that may be made of up to three parts: "LETTERS_BEFORE"+"NUMBER"+"LETTERS_AFTER". For example AB23C ABC23 23BC ABC. Is there a way to split them into an arrays of 3 elements? The operation on previous strings should produce ('AB','23','C'), ('ABC','23',''), ('','23','BC'), ('ABC','','').
Thank you in advance for any hint.
Re: Split with numbers
by BrowserUk (Patriarch) on Nov 24, 2015 at 18:31 UTC
|
#! perl -slw
use strict;
my @examples = qw[ AB23C ABC23 23BC ABC ];
m[([A-Z]*)([0-9]*)([A-Z]*)]
and printf "%s: '%s', '%s', '%s'\n", $_, $1//'', $2//'', $3//''
for @examples;
__END__
C:\test>1148522
AB23C: 'AB', '23', 'C'
ABC23: 'ABC', '23', ''
23BC: '', '23', 'BC'
ABC: 'ABC', '', ''
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
In the absence of evidence, opinion is indistinguishable from prejudice.
| [reply] [d/l] |
|
use strict;
use warnings;
use Data::Dump 'pp';
my @examples = qw[ AB23C ABC23 23BC ABC ];
my @out; push @out, [ m/([A-Z]*)([0-9]*)([A-Z]*)/ ] for @examples;
pp @out;
__END__
(
["AB", 23, "C"],
["ABC", 23, ""],
["", 23, "BC"],
["ABC", "", ""],
)
| [reply] [d/l] |
|
@out = map[ m[([A-Z]*)([0-9]*)([A-Z]*)] ], qw[ AB23C ABC23 23BC ABC ];
+;
pp \@out;;
[
["AB", 23, "C"],
["ABC", 23, ""],
["", 23, "BC"],
["ABC", "", ""],
]
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
In the absence of evidence, opinion is indistinguishable from prejudice.
| [reply] [d/l] |
|
Re: Split with numbers
by hdb (Monsignor) on Nov 24, 2015 at 18:33 UTC
|
split allows to specify a regular expression. For your application something like split /(\d+)/ should work. You need to put the regex into parentheses as you want to keep the numbers.
| [reply] [d/l] |
|
This is a good idea in general, but won't work for the OP specific requirement: ABC23 will be split into ABC and 23, but split won't generate a third empty string.
For example:
$ perl -E ' say map { qq{"$_" }} split /(\d+)/ for qw[ AB23C ABC23 23
+BC ABC ]'
"AB" "23" "C"
"ABC" "23"
"" "23" "BC"
"ABC"
| [reply] [d/l] [select] |
|
split /([0-9]+)/ , $string , 3
... but still fails for the case of xyz. | [reply] [d/l] [select] |
|
Re: Split with numbers
by Anonymous Monk on Nov 24, 2015 at 18:36 UTC
|
| [reply] |
|
|