Dear, you need regular expressions for port validation. That is, an integer value from 0 to 65535. I promise not to ask stupid questions and learn regex anymore.

  • 3
    Is it correct to use a regular schedule in such a case? IMHO - no. - vv2cc
  • Ok, then how best to proceed? - MaxMax

2 answers 2

We will not ask why you can not translate a string into a number and compare, but try to make a regular schedule :)

 ^(([0-9]{1,4})|([1-5][0-9]{4})|(6[0-4][0-9]{3})|(65[0-4][0-9]{2})|(655[0-2][0-9])|(6553[0-5]))$ 

The principle here is: take the regexp editor and enter test values, for example:

 1 23 800 8080 60000 65001 65532 65535 71234 -- не должно находить! 

And further in parts we compose the regular expression. First you need to check four-digit numbers (up to 9999), they can be any ([0-9]{1,4}) . Then five-digit to 59999 ([1-5][0-9]{4}) , then to 64999 (6[0-4][0-9]{3}) , then to 65499
(65[0-4][0-9]{2}) , then to 65529 (655[0-2][0-9]) , then to 65535 (6553[0-5])

Join groups with |

  • Why not instead use / ^ (\ d +) $ / and a comparison with 65535 in Groups? Anything clearer and shorter. - user6550
  • one
    @klopp; You can not even bathe with regular expressions, when a string consists only of a number, but simply convert the string to a number using standard language tools. - ReinRaus
  • A string can consist of any characters (well, you know, users can enter anything))), and Int.TryParse ("+ 100"); returns true. It was VERY important that the method return false with the string "+ someInt". - MaxMax
  • 3
    @dima_kot, in this case, it is better to proceed as @klopp suggests, check that the string consists only of numbers, bring the number to regular means and compare with 65535. The solutions given by me and @tolyandre are too suboptimal in speed and are Indian task. - ReinRaus
  • Yes. On sharpe, this check will look something like this: private int GetPort (string str) {if (Regex.IsMatch (str, @ "^ \ d + $")) {int port = int.Parse (str); if ((port> 0) && (port <= 65535)) return port; } return -1; } - pincher1519

I have this option for PCRE:

 preg_replace("/(?!\d)(?:(?:[0-9]{5}(?<![7-9]\.{4})(?<!6[6-9]\.{3})(?<!65[6-9]\.{2})(?<!655[4-9]\.)(?<!6553[6-9]))|[0-9]{1,4})(?!\d)/", "XX", " 65536 "); 

In this case, the regular expression does not matter where in the line the number is.