Dalija Prasnikar
Dalija Prasnikar

Reputation: 28512

Match if string contains only ASCII alphanumeric, dash, underscore and dot characters in Perl

I have following Perl script that should write OK if string contains only following characters a-z A-Z dash - underscore _ or dot . and FAIL if string contains any other character. However, it writes OK no matter what I put in string $ref.

In this example match should fail because string contains + \ and /

#!/usr/bin/perl

 print "Content-type: text/html\n\n";   

 $ref = 'abcABCZ01234+56789.htm_abc\/--a'; 

 if ($ref =~ m/[a-zA-Z_0-9\-\.]/) { print "OK\n\n"; }
 else { print "FAIL\n\n"; }

 print "<br>$ref\n\n"; 

1;

Upvotes: 1

Views: 1886

Answers (2)

Toto
Toto

Reputation: 91498

You just need to add anchors and quantifier:

if ($ref =~ /^[a-zA-Z_0-9.-]+$/) { print "OK\n\n"; }
#            ^              ^^ 

Upvotes: 2

mpapec
mpapec

Reputation: 50667

Your regex matches when it finds first char that satisfies regex class, but to make sure that all chars are inside regex class you have to state that it matches from beginning ^ to the end of the string \z,

$ref =~ m/^[a-zA-Z_0-9.-]+\z/;

Upvotes: 2

Related Questions