IP地址的Scala正则表达式模式匹配 [英] Scala regex pattern match of ip address
本文介绍了IP地址的Scala正则表达式模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不明白为什么这段代码返回 false:
I can't understand why this code returns false:
val reg = """.*(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}).*""".r
"ttt20.30.4.140ttt" match{
case reg(one, two, three, four) =>
if (host == one + "." + two + "." + three + "." + four) true else false
case _ => false
}
并且仅当我将其更改为:
and only if I change it to:
val reg = """.*(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}).*""".r
"20.30.4.140" match{
case reg(one, two, three, four) =>
if (host == one + "." + two + "." + three + "." + four) true else false
case _ => false
}
确实匹配
推荐答案
你的变体
def main( args: Array[String] ) : Unit = {
val regex = """.*(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}).*""".r
val x = "ttt20.30.4.140ttt"
x match {
case regex(ip1,ip2,ip3,ip4) => println(ip1, ip2, ip3, ip4)
case _ => println("No match.")
}
}
匹配,但不是你想要的.结果将是 (0,30,4,140) 而不是 (20,30,4,140).正如你所看到的 .*
是贪婪的,所以尽可能多地消耗输入.
matches, but not as you intend. Result will be (0,30,4,140) instead of (20,30,4,140). As you can see .*
is greedy, so consumes as much input as it can.
例如ab12
可以通过 .*(\d{1,3})
分隔成
e.g. ab12
could be separated via .*(\d{1,3})
into
ab
和12
ab1
和2
.... 这是选择的变体,因为.*
消耗尽可能多的输入
ab
and12
ab1
and2
.... this is the variant chosen, as.*
consumes as much input as it can
让
.*
不情愿(而不是贪婪),也就是.*?
所以总的来说
Make
.*
reluctant (and not greedy), that is.*?
so in total
""".*?(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}).*""".r
在第一个数字之前精确定义模式,例如如果这些只是字符,请执行
Precisely define the pattern before the first number, e.g. if these are only characters, do
"""[a-zA-Z]*(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}).*""".r
这篇关于IP地址的Scala正则表达式模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文