Re: Regular expression question



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
.



Relevant Pages

  • Re: regex problem unresolved
    ... makes regex fail, I might have already solved half of the problem. ... data file confirmed by search, I believe the fetch program first grabs all ... You have a file 1 from which you read a string, ... the regular expression make it look a bit like that). ...
    (comp.lang.perl.misc)
  • Re: Which RegEx Testing Tool Do You Prefer?
    ... public static string ReplaceAmpersand ... I used both Expresso and Regex Buddy to come up with this. ... > have to force the 2.0 Regular Expression Validator to fail when the & is ... >> create patterns of a large variety of types. ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: RegExp to capture IMAGE SRC only.
    ... OBJECT's SRC. ... You will have to define the expected string clearly. ... So you will have to fine tune your regex again and again, ... I put your regular expression in both The Regex Coach, ...
    (comp.lang.javascript)
  • RE: Split question
    ... >>first argument as a regular expression. ... it searches for the null string to split on. ... > The second one is if you include parentheses in your regex. ...
    (perl.beginners)
  • Re: Get regular expression
    ... own tree structure. ... Expression compares a string character-by character, ... regular expression solution, which was about as close as one could get to ... the structure of the hierarchy can be inferred by using ...
    (microsoft.public.dotnet.languages.csharp)