MAC 地址的 Scala REGEX 匹配

Scala REGEX match for MAC address

晚上好,Whosebug,

我被困在无法让 Scala 正则表达式匹配正常运行的地方,这是我的代码

private def handle_read(packet: TFTPReadRequestPacket, tftp_io: TFTP): Unit = {

    val MAC_REGEX = "([0-9A-F]{2}[:-]){5}([0-9A-F]{2})".r
    packet.getFilename match {
        case MAC_REGEX(a) => println(s"Client is coming from $a")
    }

}

当正则表达式为 ([0-9A-F]{2}[:-]) 并且我请求文件 70- 时它很好并且吐出客户端是 "coming from 70",但是当它是完整的正则表达式并且我请求 70-CD-60-74-24-9C 它抛出这样的异常

[ERROR] [04/28/2015 21:25:27.818] [polydeploy-baremetal-akka.actor.default-dispatcher-4] [akka://polydeploy-baremetal/user/TFTP_Queue] 70-CD-60-74-24-9C (of class java.lang.String)
scala.MatchError: 70-CD-60-74-24-9C (of class java.lang.String)
    at com.polydeploy.baremetal.TFTPQueue$.handle_read(TFTPQueue.scala:40)
    at com.polydeploy.baremetal.TFTPQueue$.com$polydeploy$baremetal$TFTPQueue$$handle_request(TFTPQueue.scala:33)
    at com.polydeploy.baremetal.TFTPQueue$$anonfun$receive.applyOrElse(TFTPQueue.scala:14)
    at akka.actor.Actor$class.aroundReceive(Actor.scala:467)
    at com.polydeploy.baremetal.TFTPQueue$.aroundReceive(TFTPQueue.scala:10)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:516)
    at akka.actor.ActorCell.invoke(ActorCell.scala:487)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:254)
    at akka.dispatch.Mailbox.run(Mailbox.scala:221)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:231)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

我想要尝试和积累的是能够让 TFTP 请求进入 pxelinux.cfg/01-70-CD-60-74-24-9C 并提取 MAC 地址。

非常感谢任何帮助!

谢谢,利亚姆。

When the regex is ([0-9A-F]{2}[:-]) and I request for the file 70- it is fine

这是因为,在这种情况下,您的正则表达式只包含一个组。

这对我有用:

val MAC_REGEX = "(([0-9A-F]{2}[:-]){5}([0-9A-F]{2}))".r
"70-CD-60-74-24-9C" match {
    case MAC_REGEX(a, _*) => println(s"Client is coming from $a")
} 
// prints "Client is coming from 70-CD-60-74-24-9C"

之所以有效,是因为我用一个组包裹了整个正则表达式。 a 捕获该外部组,而 _* 是所有其他组的一系列忽略匹配项。显然 Regex 的提取器 returns 一个列表,每个捕获组都有一个元素。

不过我觉得有更好的方法...