user4035
user4035

Reputation: 23749

\d+ regexp ignores minus at the beginning

I faced behaviour of Perl, that I can't explain:

#!/usr/bin/perl

use strict;
use warnings;

my $number = -10;
if ($number =~ /\d+/) {
    print $number;
}

This prints -10, despite the fact, that

Why does it ignore minus at the beginning?

Upvotes: 2

Views: 298

Answers (4)

Borodin
Borodin

Reputation: 126742

You can write this as

if ($number and $number !~ /\D/) {
  print $number;
}

which checks that the string isn't zero-length and doesn't contain any non-digit characters.

Upvotes: 1

Victor Bocharsky
Victor Bocharsky

Reputation: 12306

Minus is a symbol, not number, so use:

if ($number =~ /^-?\d+$/) {
    print $number;
}

-? say that minus - symbol can meet one or zero times

Upvotes: 2

Jassi
Jassi

Reputation: 541

Whatever is the purpose of \d+ or [0-9]+ , its doing correct thing only. It depends upon your requirement what else you want like mixture of integers or just negative number to match or positive number to match or beginning, end, anywhere etc. All depends upon the pattern you want to develop.

Upvotes: 0

Lajos Veres
Lajos Veres

Reputation: 13725

You should match against the beginning of the string also with a ^:

if ($number =~ /^\d+/) {

Upvotes: 7

Related Questions