1

Consider a regex for testing port numbers.

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

This is not valid in Android.

Any idea what a port number regex should look like in Android?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
MojoDK
  • 4,410
  • 10
  • 42
  • 80

3 Answers3

12

Generally, regex isn't that great for numerical validation. I'd recommend using Integer.parseInt on a matched group and then check that to see if it's less than 65536.

Ross Light
  • 4,769
  • 1
  • 26
  • 37
  • Agreed. I tried to validate an integer range for a tokenizer with regex once and got super frustrated trying to get it right. Match [0-9]+ and then get it into a number format. – colithium Oct 08 '10 at 22:49
2

"(6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3})" works on a Java Regex test page assuming that you are writing Java code. You probably have to escape the backslashes for the Java string literal to work. However, this expression does not thing that zero is a valid port number.

D.Shawley
  • 58,213
  • 10
  • 98
  • 113
-1

It is old one, but in case someone is wondering how to use tryparse, a mentioned by one of developers:

int portNumber;
if (int.TryParse(inputPortValue, out portNumber)
    && portNumber >= 256
    && portNumber <= 0){
     error = "Invalid Port: " + inputPortValue
     ". Please verify.";
     return false;
     }
Sachin Varma
  • 2,175
  • 4
  • 28
  • 39
sgupta
  • 535
  • 4
  • 8
  • It is in C# actually. https://stackoverflow.com/questions/15294878/how-the-int-tryparse-actually-works Somehow missed it is Android question or probably was edited later. – sgupta Feb 24 '18 at 03:17