Cody Fendant has asked for the wisdom of the Perl Monks concerning the following question:
Trying to match a pattern which is roughly a-or-b-followed by digits or digits-followed-by-a-or-b.
use strict; use warnings; use Data::Dumper; $Data::Dumper::Indent = 0; my $string_one = 'foo bar [a21] plus (b23) baz bax'; my @string_one_results = $string_one =~ m { (a|b) (\d+) }gx; print "RESULTS: " , Dumper(\@string_one_results), $/; # RESULTS: $VAR1 = ['a','21','b','23'];
So far so good for the first pattern. Here's the other
my $string_two = 'foo bar [21a] plus (23b) baz bax'; my @string_two_results = $string_two =~ m{ (\d+) (a|b) }gx; print "RESULTS: " , Dumper(\@string_two_results), $/; # RESULTS: $VAR1 = ['21','a','23','b'];
The second regex matches fine for that other format. Here's what I've been struggling over for half an hour or so: what if the two formats are mixed up?
Shouldn't I be able to come up with a regex matching either pattern?
my $string_three = 'foo bar [21a] plus (b23) baz bax'; my @string_three_results = $string_three =~ m{ (\d+) (a|b) | (a|b) (\d ++) }gx; print "RESULTS: " , Dumper(\@string_three_results), $/; # RESULTS: $VAR1 = ['21','a',undef,undef,undef,undef,'b','23'];
Please help me out, Monks. What am I doing wrong and what are the undefs in my @results?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Complex regex question
by Athanasius (Archbishop) on Sep 25, 2019 at 06:39 UTC | |
|
Re: Complex regex question
by AnomalousMonk (Archbishop) on Sep 25, 2019 at 06:47 UTC | |
|
Re: Complex regex question
by tybalt89 (Monsignor) on Sep 25, 2019 at 14:16 UTC | |
|
Re: Complex regex question
by AnomalousMonk (Archbishop) on Sep 25, 2019 at 16:22 UTC | |
by rsFalse (Chaplain) on Sep 25, 2019 at 18:52 UTC | |
|
Re: Complex regex question
by beech (Parson) on Sep 25, 2019 at 06:45 UTC | |
by AnomalousMonk (Archbishop) on Sep 25, 2019 at 06:58 UTC |