Answer the question
In order to leave comments, you need to log in
String#scan. How to write a regular expression to search for an ip address in a string?
Good afternoon, ladies and gentlemen. Surely someone came across, tell me a regular expression to search for an ip address in a string.
str.scan(/.../).
Thank you in advance.
Answer the question
In order to leave comments, you need to log in
I slightly illustrated the answer from Vlad Chernik and added validation of the found addresses using the ipaddr standard library:
require 'ipaddr'
text = "Proxy IP Proxy Port Last Check Proxy
Speed Proxy Country Anonymity 118.99.81.204118.99.81.204 8080 34 sec
Indonesia - Tangerang Transparent 2.184.31.2 8080 58 sec Iran
Transparent 93.126.11.189 8080 1 min Iran -
Esfahan Transparent 202.118.236.130 7777 1 min
China - Harbin Transparent 62.201.207.9 8080 1 min Iraq
Transparent 219.143.244.170 8899 1 min China -
Beijing Transparent 66.63.235.97 8080 1
min United States - Somerville Transparent 27.191.194.106 8080 1
min China Transparent 200.195.141.178 8080 2 min
Brazil Transparent 210.101.131.232 8080 2 min
South Korea - Seoul Transparent 218.75.205.44 9999 2 min
China - Changsha Transparent212.119.97.198 3128 2 min Russia - Moscow
Transparent 999.999.999.99 213.11.23.999
Your public IP address is 41.110.14.41 - Learn more"
valid_ip = []
text.scan(/\b(?:\d{1,3}\.){3}\d{1,3}\b/).map do |ip|
valid_ip << ip if !(IPAddr.new(ip) rescue nil).nil?
end
puts valid_ip
require 'resolv'
str = "178.248.232.5"
case str
when Resolv::IPv4::Regex
puts "It's a valid IPv4 address."
when Resolv::IPv6::Regex
puts "It's a valid IPv6 address."
else
puts "It's not a valid IP address."
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question