Tbpgr Blog

元エンジニア 人事 tbpgr(てぃーびー) のブログ

書籍 Regular Expressions Cookbook | Matching IPv4 Addresses

パンくず

書籍 Regular Expressions Cookbook
Matching IPv4 Addresses

概要

IPv4のバリデーションについて

サンプル

subject = Array.new
subject << "192.168.0.1" # => match
subject << "255.255.255.255" # => match
subject << "1.1.1.1" # => match
subject << "1111.1.1.1"

ip = "(?:25[0-5]|2[0-4][\d]|[01]?[0-9]?[0-9])"
pattern = /\b(?:#{ip}\.){3}#{ip}\b/
subject.each_with_index {|each_subject,i|puts "#{i}:#{each_subject.scan(pattern)}"}

出力

0:["192.168.0.1"]
1:["255.255.255.255"]
2:["1.1.1.1"]
3:[]