2019年5月23日 星期四

Kotlin學習筆記(25) 檢查字串是數字 ?

Kotlin學習筆記(25) 檢查字串是數字 ? 
源自於 https://www.programiz.com/kotlin-programming/examples/check-string-numeric

val string = "-1234.15"
var numeric = true

fun main(args: Array<String>) {
    numeric = string.matches("-?\\d+(\\.\\d+)?".toRegex())
    if (numeric)
        println("$string is a number")
    else
        println("$string is not a number")
}

輸出畫面
-1234.15 is a number


In the matches() method,
  • -? allows zero or more - for negative numbers in the string.
  • \\d+ checks the string must have atleast 1 or more numbers (\\d).
  • (\\.\\d+)? allows zero or more of the given pattern (\\.\\d+) in which
    • \\. checks if the string contains . (decimal points) or not
    • If yes, it should be followed by at least one or more number \\d+.
Here's the equivalent Java code: Java program to check if a string is numeric or n

沒有留言:

張貼留言

零成本學 ESP32!在 Wokwi 打造你的第一個微型氣象站 (ESP32 + DHT22 + 1602 LCD)

零成本學 ESP32!在 Wokwi 打造你的第一個微型氣象站(溫度 濕度) (ESP32 + DHT22 + 1602 LCD) 想學物聯網(IoT)與 ESP32 電子實作,卻擔心接線與電壓規範搞砸嗎?透過強大的線上模擬器 Wokwi ,我們不需要花費任何硬體費用,打開瀏覽器...