簡體   English   中英

IP地址的Scala正則表達式模式匹配

[英]Scala regex pattern match of ip address

我不明白為什么這段代碼返回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
      }

並且僅當我將其更改為:

  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)。 如您所見.*是貪婪的,因此會消耗盡可能多的輸入。

例如ab12可以通過.*(\\d{1,3})分隔為

  • ab12
  • ab12 ....這是選擇的變體,因為.*會消耗盡可能多的輸入

解決方案

  1. 使.*不願意(而不是貪婪),也就是.*? 所以總共

     """.*?(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3}).*""".r 
  2. 精確定義第一個數字之前的模式,例如,如果這些僅是字符,請執行

     """[a-zA-Z]*(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3}).*""".r 

您應該使用勉強的量詞而不是貪婪的量詞

val reg = """.*?(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}).*""".r

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM