简体   繁体   中英

Perl regular expression to match input for port numbers

I would like to write a regular expression that would only accept valid input that would qualify as a port number. I want to only accept input for the characters 0-9 and no special characters. The number should not be longer than 5 characters.

I read user input using this method.

my $port_number = <>;

I know that the regular expression should look something like this.

^[0-9]*$

How do I combine the regular expression with the reading of the command line input without using an if statement?

Try this code:

$result = ($port_number =~ m/^[0-9]{1,5}$/);

$result will be set to 1 if the $port_number matches your criteria, and will be set to 0 otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM