How to match several numbers only?

Viewed 67

Currently, I have one issue to match several numbers only.

for example:

my $input1 = "1234 abc test";     - > expect - match and return 1234
my $input2 = " 1234 abc test";    - > expect - match and return 1234
my $input3 = "abc test 1234";     - > expect - match and return 1234
my $input4 = "a1234 test";         not match
my $input5 = "1234- abc test";     not match
my $input6 = "abc 12345 test";     not match

For the above 6 examples, only input1, input2, and input3 need to return 1234. Others will return not matched. How to code the regular expression like that?

I try to do this, but it will not work for input1 and input3.

if $input =~ /\s+(\d{4,4})\s+/{

}
3 Answers
/(?:^|\s)(\d{4})(?:\z|\s)/a

or

/(?<!\S)(\d{4})(?!\S)/a   # Not proceeded by a non-space and not followed by a non-space.

(\d normally matches 630 different Code Points. The /a causes it to only match [0-9] instead.)

Use an alternative: whitespace or beginning/end of string.

$input =~ /(?:^|\s)(\d{4})(?:$|\s)/

Also note that \d matches digits in other writing systems like "೬". Use [0-9] or the /a modifier to only match ascii digits.

I am not a fan of ugly regex if it can be split to simplify the code.... This Perl will work it does a single pass to grab any values and double checks for format in the second pass...

#!/usr/bin/env perl

$input[1] = "1234 abc test";   #  - > expect - match and return 1234
$input[2] = " 1234 abc test";  #  - > expect - match and return 1234
$input[3] = "abc test 1234";   #  - > expect - match and return 1234
$input[4] = "a1234 test";      #   not match
$input[5] = "1234- abc test";  #   not match
$input[6] = "abc 12345 test";  #   not match

for $input (@input) {
#   $input = $input[$i];
    next if $input !~ /(.?\d{4}.?)/;
    $val = $1;
    next if $val !~ /^\s?(\d{4})\s?$/;
    $val = $1;

    printf "%s\n", $val;
}
Related