Reputation: 12595
I want to make sure a string has the format of an ip address. I don't need anything too specific. I just want to check if there are three .
in the string. I can check if there is one .
in there like this:
str.include? '.'
But how can I check for multiple .
?
Thanks!
Upvotes: 3
Views: 2248
Reputation: 160631
This is one of those "don't reinvent a working wheel" cases.
Ruby comes with the IPAddr class, which is used to manipulate IP addresses. Regular expressions are included in the class that are used to parse the target IP string into octets. Reuse IPAddr::RE_IPV4ADDRLIKE
:
require 'ipaddr'
IPAddr::RE_IPV4ADDRLIKE
=> /
\A
(\d+) \. (\d+) \. (\d+) \. (\d+)
\z
/x
This pattern matches against an entire string because of \A
and \z
. Here are some range tests:
'one.two.three.four'[IPAddr::RE_IPV4ADDRLIKE]
=> nil
'1.2.3.4'[IPAddr::RE_IPV4ADDRLIKE]
=> "1.2.3.4"
'foo 1.2.3.4 bar'[IPAddr::RE_IPV4ADDRLIKE]
=> nil
'128.255.255.255'[IPAddr::RE_IPV4ADDRLIKE]
=> "128.255.255.255"
'999.999.999.999'[IPAddr::RE_IPV4ADDRLIKE]
=> "999.999.999.999"
'0000.0000.0000.0000'[IPAddr::RE_IPV4ADDRLIKE]
=> "0000.0000.0000.0000"
If, as you work with IP addresses, you need more power, check out the IPAddress gem. It's very nice.
To know if you've actually received a valid IP address, see the answer by @DarshanComputing.
Upvotes: 7
Reputation: 34071
String#count counts the number of occurrences of each character in its argument:
"127.0.0.1".count('.')
# => 3
So to answer your question literally,
"127.0.0.1".count('.') == 3
# => true
In reality, I'd be hard-pressed to consider that even a poor IP address validator. I'd probably do something like this:
require 'ipaddr'
def validateIP(s)
!!IPAddr.new(s) rescue false
end
validateIP('127.0.0.1')
# => true
validateIP('999.0.0.1')
# => false
Upvotes: 7
Reputation: 17189
String has a .count
method which takes in a character.
str.count('.') == 3
EDIT:
Since you are looking to match an IP address, www.regular-expressions.info has an example of capturing an IP using Regular Expressions.
if possible_ip_address.match(%r{\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b})
# code here...
end
This will capture addresses that aren't valid (such as 999.999.0.1) but it will prevent false positives like
"not.real.ip.address".count('.') == 3 #=> true
Upvotes: 8