Neil Middleton
Neil Middleton

Reputation: 22240

Matching strings with wildcards in Ruby

I have some IP addresses:

127.0.0.1
192.168.*
200.*

How can I simply match a given IP address against these ranges quickly and easily. There could potentially be thousands of patterns such as the above.

Upvotes: 0

Views: 496

Answers (2)

Holger Just
Holger Just

Reputation: 55833

To save you from pain, you should use CIDR addresses instead of your string wildcards. This is the generally accepted notation for networks and sane ranges of IPs. You will find a wide support for this notation in about any language.

In your case, the networks would be

127.0.0.1/32 (or just simply 127.0.0.1)
192.168.0.0/16
200.0.0.0/8

The you can use something like the built-in IPAddr class or the IPAddress gem to parse those.

With the IPAddress gem, you can then do something like this (untested):

range = IPAddress("192.168.0.0/16")
ip = IPAddress("192.168.3.5")
range.include? ip # returns true

Upvotes: 3

nkm
nkm

Reputation: 5914

Following should match,

\b(?:(?: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]?)\b

Upvotes: 0

Related Questions