Re: Regular expression question
- From: rob.dixon@xxxxxxx (Rob Dixon)
- Date: Tue, 07 Oct 2008 21:37:04 +0100
irata wrote:
can someone explain me, why this short regex don't give the result I
expect:
perl -e '$text = "(7) 32"; printf "[%s][%s]\n", ( $text =~ /\((\d+)
\)\s+(\d+)/ )'
I supposed that the output is "[7][32]", but the output is "[][]". I
don't know why...
Your regular expression isn't matching the object string. If you had written a
Perl script and added
use strict;
use warnings;
you would have seen the warning message 'Use of uninitialized value in printf'
which shows that the captures have failed. You should really check the success
of a pattern match before you use the captured data, so something like this
use strict;
use warnings;
my $text = "(7) 32";
$text =~ /\((\d+) \)\s+(\d+)/ or die;
printf "[%s][%s]\n", $1, $2;
Because your email client has wrapped the source line with the regular
expression I cannot be certain why the match failed, but I would guess that the
regular expression insists on a single space character after the string of
digits within the parentheses. Your string has no space there so the match
fails. Changing the regex to this
/\((\d+)\)\s+(\d+)/
will give you the result you expect, although I have no way of knowing whether
that is the right pattern for you to use.
HTH,
Rob
.
- References:
- Regular expression question
- From: Irata
- Regular expression question
- Prev by Date: efficient way to write code
- Next by Date: Re: How to check empty hash value properly?
- Previous by thread: Re: Regular expression question
- Next by thread: how can i untain $ARGV from a perl script extending snmp?
- Index(es):
Relevant Pages
|