Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

my $text = 'my model TT1986 is 6 months old"; #my $text = 'my model TT1986 is 12 months old"; $text =~ /(\d?\d)/; print $1;
I'm trying to extract the age digits only but it extracts the wrong digits (19) .
$text =~ /^\b(\d?\d)/; print $1;
doesn't print anything. What's a girl supposed to do?? :)

Replies are listed 'Best First'.
Re: Regex extracting a number from numbers and text
by ikegami (Patriarch) on Oct 17, 2006 at 16:51 UTC
    Very close. You are right to use \b. The problem is that you also used ^ which means "start of string". The number is not located at the start of the string.
    $text =~ /\b(\d+)/

    Update: By the way, you shouldn't use $1 unless you made sure the match succeeded.

    if ($text =~ /\b(\d+)\b/) { print("Matched $1\n"); }

    Update: Other solutions:

    # The first standalone number. $text =~ /\b(\d+)\b/
    # By context. $text =~ /(\d+) months? old/
    # The last number. $text =~ /^.*\b(\d+)/
Re: Regex extracting a number from numbers and text
by Anonymous Monk on Oct 17, 2006 at 16:57 UTC
    So near yet so far! Thanks for your help.