简体   繁体   English

在 Scala 中匹配 IP 地址

[英]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". Scala 新手,我编写了这段代码来匹配 IP 地址,但结果是“不匹配”。

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.结果: No match.

I have verified that the Regex pattern works as expected.我已验证 Regex 模式按预期工作。

What am I missing here?我在这里缺少什么?

There are several issues:有几个问题:

  • An issue with your regex that does not match the full IP address.与完整 IP 地址不匹配的正则表达式问题。 You can use a well-known IP address validation regex from regular-expressions.info.您可以使用来自regular-expressions.info 的众所周知的IP 地址验证正则表达式
  • match requires a full string match match需要完整的字符串匹配
  • match also requires a capturing group in the pattern. match还需要模式中的捕获组。 If you do not want to specify the group, you need regex() => println(ip) to just check if the regex matches a string.如果您不想指定组, regex() => println(ip)需要regex() => println(ip)来检查正则表达式是否与字符串匹配。

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 .请参阅Scala 代码演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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