天天看點

Kotlin中正規表達式分析

一、首先來看一下Java中的正規表達式的寫法

package cn.kotliner.java.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created wangdong
 * 用正規表達式,從字元串中提取電話号碼
 */
public class Main {
    public static void main(String... args) {
        String source = "Hello, This my phone number: 010-12345678. ";
        String pattern = ".*(\\d{3}-\\d{8}).*";
        Matcher matcher = Pattern.compile(pattern).matcher(source);

        while(matcher.find()){
            System.out.println(matcher.group());
            System.out.println(matcher.group(1));
        }
    }
}
           

運作結果:

Hello, This my phone number: 010-12345678. 
010-12345678           

二、接下來看一下Kotlin中的正規表達式的寫法

package cn.kotliner.kotlin.regex

import java.util.regex.Pattern

/**
 * Created by wangdong
 * 正規表達式
 */
fun main(args: Array<String>) {
    val source = "Hello, This my phone number: 010-12345678. "
    //用Raw字元串定義正規表達式
    val pattern = """.*(\d{3}-\d{8}).*"""

    //将正則規則傳入到Regex中,調用findAll方法,将需要查詢的源傳進來
    //将它變成一個list,将它MatchResult打平用flatMap,得到groupValues集合,用forEach将他列印出坑了
    Regex(pattern).findAll(source).toList().flatMap(MatchResult::groupValues).forEach(::println)

}           
Hello, This my phone number: 010-12345678. 
010-12345678           

好啦,結束啦