[英]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:有几个问题:
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.