LoginSignup
3
3

More than 5 years have passed since last update.

Parser CombinatorでIPアドレスのチェック

Last updated at Posted at 2014-02-05

まだちょっと試行錯誤しなきゃいけないと思いますが、とりあえずIPアドレスをチェックする方法。

import java.net.{InetAddress,UnknownHostException}
import util.parsing.combinator.RegexParsers

object IpParsers extends RegexParsers {
  def ipAddress: Parser[String] = """[0-9a-fA-F:\.]+""".r.withFilter { str =>
    try {
      val addr = InetAddress.getByName(str)
      true
    } catch {
      case e: UnknownHostException => false
    }
  }
}
  1. 前提として、IPv4またはIPv6文字列をまとめて扱い、ざっくりと文字列の範囲を選びとる。(最初の正規表現マッチ)
  2. withFilterで抽出した文字列の検証を追加
  3. InetAddress.getByNameでIPアドレスとみなせるかどうかフィルタ

結果は見つかった文字列(ex. 192.168.0.0, ::1)になる。
ParserクラスにwithFilterflatMapなどのMonadicなメソッドが定義されてるのは知らなかった。

余談

Scala 2.10 なら Try が使えますね。エラー処理はこう書いたほうがすっきりするかも。

util.Try(InetAddress.getByName(str)).isSuccess

この場合、例外は全て握りつぶしてfalseを返す仕様。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3