Tobin Cataldo has asked for the wisdom of the Perl Monks concerning the following question:
Greetings,
I am in need of guidance. I am attempting to capture elements from a string which may or may not exist.
Two possible (overly simplistic) strings are below, and I need to capture a, b and c (if they exist).
my $input1 = 'a=1 gibberish b=2 c=3'; my $input2 = 'a=1 gibberish c=3';
I threw this together with a conditional (?) on the b element. I don't get the results I expected, which probably means my expectations are wrong. Any way to get what I want with just a single pass?
my $input1 = 'a=1 gibberish b=2 c=3'; my $input2 = 'a=1 gibberish c=3'; # normal capture my $match1 = '^(?<a>a=(\d)).*?(?<b>b=(\d)).*?(?<c>c=(\d))$'; # conditional capture my $match2 = '^(?<a>a=(\d)).*?(?<b>b=(\d))?.*?(?<c>c=(\d))$'; # using $match1 print "\n\nUsing match1 ---> $match1\n\n"; if ($input1 =~ m/$match1/){ print "Input1: a is $+{a} and b is $+{b} a +nd c is $+{c}\n"; } else { print "Input1: didn't match\n"; } if ($input2 =~ m/$match1/){ print "Input2: a is $+{a} and b is $+{b} a +nd c is $+{c}\n"; } else { print "Input2: didn't match\n"; } # using $match2 # conditional capture on the b element print "\n\nUsing match2 ---> $match2\n\n"; if ($input1 =~ m/$match2/){ print "Input1: a is $+{a} and b is $+{b} a +nd c is $+{c}\n"; } else { print "Input1: didn't match\n"; } if ($input2 =~ m/$match2/){ print "Input2: a is $+{a} and b is $+{b} a +nd c is $+{c}\n"; } else { print "Input2: didn't match\n"; }
Output :
Using match1 ---> ^(?<a>a=(\d)).*?(?<b>b=(\d)).*?(?<c>c=(\d))$ Input1: a is a=1 and b is b=2 and c is c=3 Input2: didn't match Using match2 ---> ^(?<a>a=(\d)).*?(?<b>b=(\d))?.*?(?<c>c=(\d))$ Input1: a is a=1 and b is and c is c=3 Input2: a is a=1 and b is and c is c=3
Thanks,
Tobin
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: regular expression help
by Fletch (Bishop) on Dec 16, 2009 at 18:01 UTC | |
|
Re: regular expression help
by ikegami (Patriarch) on Dec 16, 2009 at 17:59 UTC | |
|
Re: regular expression help
by jwkrahn (Abbot) on Dec 16, 2009 at 18:09 UTC | |
by Tobin Cataldo (Monk) on Dec 16, 2009 at 21:54 UTC | |
|
Re: regular expression help
by AnomalousMonk (Archbishop) on Dec 16, 2009 at 20:10 UTC |