简体   繁体   中英

Matching an IP address in Scala

New to Scala, I've written this piece of code to match IP addresses, but results with "No Match".

val regex = """^(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})$""".r
val i = "10.20.30.40"

def isValidIP(ip: String) = ip match {
    case regex(ip) => println(ip)
    case _ => println("No match.")
 }

isValidIP(i)

Result: No match.

I have verified that the Regex pattern works as expected.

What am I missing here?

There are several issues:

  • An issue with your regex that does not match the full IP address. You can use a well-known IP address validation regex from regular-expressions.info.
  • match requires a full string match
  • match also requires a capturing group in the pattern. If you do not want to specify the group, you need regex() => println(ip) to just check if the regex matches a string.

You can fix your code using

val regex = """(?:(?: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]?)""".r
val i = "10.20.30.40"

def isValidIP(ip: String) = ip match {
    case regex() => println(ip)
    case _ => println("No match.")
}

isValidIP(i)

See the Scala code demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM