I have a string I need to parse. It meets the following requirements:
Example strings I may see:
I need to build a Perl hash of this string. If I could guarantee it was 1 pair I would do something like this:
$string =~ /([A-Z][A-Z])([0-9]+)/
$key = $1
$value = $2
$hash{$key} = $value
For multiple strings, I could potentially do something where after each match of the above regex, I take a substring of the original string (exempting the first match) and then search again. However, I'm sure there's a more clever, perl-esque way to achieve this.
Wishing I didn't have such a crappy data source to deal with-
Jonathan
In a list context with the global flag, a regex will return all matched substrings:
use Data::Dumper;
@strs = (
'AB1234',
'AB1234 BC2345',
'AB1234BC2345',
'',
'AB12345601BC1234CD1232PE2343',
'AB12345601 BC1234 CD1232 PE2343'
);
for $str (@strs) {
# The money line
%parts = ($str =~ /([A-Z][A-Z])(\d+)/g);
print Dumper(\%parts);
}
For greater opacity, remove the parentheses around the pattern matching: %parts = $str =~ /([A-Z][A-Z])(\d+)/g;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With