user965241
user965241

Reputation: 33

how to check optional variable length of number String?

What I am trying to validate something like IP address,

it maybe attach with a port or not. let me say: 10.12.1.100 and 10.12.1.100:8080 are all right.

I create something like this:

^10\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))([-+]?(:|\d[1,4]))$

however, it does not work for: 10.12.1.100:8080 parts. how to implements this part ([-+]?(:|\d[1,4]))?

if I remove ([-+]?(:|\d[1,4]));it will valid 10.12.1.100 part right.

Thanks,

Upvotes: 0

Views: 134

Answers (2)

Brian
Brian

Reputation: 4984

Your specific pattern seems like it is doing some pretty specific IP matching, otherwise i'd suggest using something like @burning_LEGION has suggested. I'm guessing there is something specific to your scenario that goes outside normal IP parsing.

I'm only extending your current pattern because I assume you require the group structure to stay the same. otherwise I'd suggest a rewrite.

But to fix your specific example, try replacing ([-+]?(:|\d[1,4]))$ with ([-+]?(:\d{1,5}))?$

Upvotes: 0

burning_LEGION
burning_LEGION

Reputation: 13450

use this regex ^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:\d{1,5})?$

Upvotes: 1

Related Questions