KennC. KennC. - 1 year ago 133
Javascript Question

javascript regular expression to check for IP addresses

I have several ip addresses like:




What type of regular expression should I write if I want to search for the all the 3 ip addresses? Eg, if I do
(I will be able to search for all 3 ip addresses)

What I can do now is something like:
but it can't seems to work well.


Answer Source

The regex you've got already has several problems:

Firstly, it contains dots. In regex, a dot means "match any character", where you need to match just an actual dot. For this, you need to escape it, so put a back-slash in front of the dots.

Secondly, but you're matching any three digits in each section. This means you'll match any number between 0 and 999, which obviously contains a lot of invalid IP address numbers.

This can be solved by making the number matching more complex; there are other answers on this site which explain how to do that, but frankly it's not worth the effort -- in my opinion, you'd be much better off splitting the string by the dots, and then just validating the four blocks as numeric integer ranges -- ie:

if(block > 0 && block <256) {....}

Hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download