Taiwan Kotlin User Group

Logo

Taiwan Kotlin User Group 的網站,在台灣推廣 Kotlin 程式語言,舉辦相關活動。如果對 Kotlin 有興趣,想要多瞭解一些,歡迎來我們的社群一起聚會!

View My GitHub Profile

Kotlin 正規表達式慣用寫法

取代字串前後的文字

在 Java 內,可以使用 replaceFirst()replaceAll() 函數。

replaceAll() 接收正規表達式做為參數

我們可以用 ##$ 來替換字串結尾為 ## 的內容

String input = "##place##holder##";
String result = input.replaceFirst("##", "").replaceAll("##$", "");
System.out.println(result); // place##holder

在 Kotlin 內,可以使用 removeSurrounding() 函數

取代字串前後的 ##

fun main() {
    val input = "##place##holder##"
    val result = input.removeSurrounding("##")
    println(result) // place##holder
}

取代字串中出現的某個樣式

在 Java 內,可以使用 Pattern 類別和 Matcher 類別

比方說我們想隱藏資料內的用戶名和密碼

String input = "login: Pokemon5, password: 1q2w3e4r5t";
Pattern pattern = Pattern.compile("\\w*\\d+\\w*");
Matcher matcher = pattern.matcher(input);
String replacementResult = matcher.replaceAll(it -> "xxx");
System.out.println("Anonymized input: '" + replacementResult + "'");
// Anonymized input: 'login: xxx, password: xxx'

在 Kotlin 內,可以使用 Regex 類別

來簡化正規表達式操作

另外,利用原始字串可以減少我們使用反斜線的次數

fun main() {
    val input = "login: Pokemon5, password: 1q2w3e4r5t"
    val regex = Regex("""\w*\d+\w*""") // raw string
    val replacementResult = regex.replace(input, replacement = "xxx")
    println("Anonymized input: '$replacementResult'")
	  // Anonymized input: 'login: xxx, password: xxx'
}

想看更多範例嗎?

可以看看

或加入 kotlin.tips 的 Kotlin 讀書會