简体   繁体   English

Perl正则表达式以匹配端口号的输入

[英]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. 我只想接受0-9字符的输入,而不能输入特殊字符。 The number should not be longer than 5 characters. 该数字不能超过5个字符。

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? 如何在不使用if语句的情况下将正则表达式与命令行输入的读取结合起来?

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. 如果$port_number符合您的条件,则$result将设置为1,否则将设置为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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