perlfoo
perlfoo

Reputation: 11

Need help with regular expression matching

Given:

$num = "3";

$num_list = "30 3 42 54";

How can I match the "3" and not the "30"? The number order will always be changing.

I tried:

if ($num_list =~ /(\s?$num\s+/)

Unfortunately it matches the "3" in "30". Not sure how to fix it. I know it's because of the ? means 0 or 1.

Your help is much appreciated!

Upvotes: 1

Views: 120

Answers (5)

ikegami
ikegami

Reputation: 385789

A solution that's great if you're going to check if a lot of numbers are in $num_list:

my $pat = join '|', map quotemeta, split " ", $num_list;
my $re = qr/^(?:$pat)\z/;

$num =~ $re

A solution that's great if you're going to check if a lot of numbers are in $num_list:

my %num_list = map { $_ => 1 } split " ", $num_list;

$num_list{$num}

A solution that doesn't require regexp (great for SQL):

index(" $num_list ", " $num ") >= 0

Simple solutions:

" $num_list " =~ / $num /

$num_list =~ /(?<!\S)$num(?!\S)/

$num_list =~ /\b$num\b/

grep { $_ == $num } split " ", $num_list

Upvotes: 2

Howard
Howard

Reputation: 39197

Try using word boundaries:

/\b$num\b/

\b will either match start or end of string or any boundary between word character and non-word character (i.e. between [0-9a-zA-Z_] and not [0-9a-zA-Z_]).

Upvotes: 5

ololo
ololo

Reputation: 108

Maybe something like:

$num_list = "30 3 42 54";
$num = "3";
@arr = explode(" ", $num_list);

if (scalar grep {$_ eq $num} @num_list) {
    print "Zuko!\n";
}

Upvotes: 0

Alnitak
Alnitak

Reputation: 339816

How about not using regexps at all?

 $num = 3;
 @num_list = qw[30 3 42 54];
 if (grep { $_ == $num } @num_list) {
    ...
 }

Upvotes: 1

ANisus
ANisus

Reputation: 77965

From what I know, Perl uses the same regex as preg_match in PHP
Then you can try the following:

/(?<=^|\s)($num)(?=$|\s)/

I should have a start or whitespace before the 3, and an end or whitespace afterwards

Upvotes: 0

Related Questions