天天看點

Java正規表達式的簡單介紹以及使用

正規表達式主要是為了友善我們提取一個字元串中感興趣的部分,尤其在爬蟲中應用廣泛。我們下面就簡單介紹一下其用法。并不做深入研究,隻是介紹其使用的方法。

1、matches方法的介紹

這個方法主要是确定給定的字元串是否由你給定的規則組成,什麼意思呢。打個比方,

I am Chinese

,這句話是不是由

英文字母+空格組成

。是以他的正則字元串就是

"(\\w+ *)+"

(注意中間有個空格,且由于最後一個字元後面沒有空格,是以要用

*

進行比對,表示可以沒有或者有多個)。這個方法要求完全比對。

這個方法傳回的是一個Boolean值,具體用法:

public class Test01 {
    public static void main(String[] args) {
        String string = "123456789abc";
        String regex2 = "(\w+ *)+";
        //方式一
        boolean matches = string.matches(regex2);
        System.out.println("matches = " + matches);

		//方式二
        boolean matches5 = Pattern.matches(regex2, string);
        System.out.println("matches5 = " + matches5);

		//方式三
        Pattern compile = Pattern.compile(regex2);
        Matcher matcher = compile.matcher(string);
        boolean matches6 = matcher.matches();
        System.out.println("matches6 = " + matches6);
    }
}
           

2、find用法

這個就是matches方法的寬松版,不要求完全比對,隻要求包含就可以,類似于contains方法。

Pattern compile = Pattern.compile(regex2);
Matcher matcher = compile.matcher(string);
boolean matches = matcher.matches();
           

3、如何提取我們感興趣的字元串呢

使用group

測試字元串

str = “I am Chinese 我為武漢加油”

,提取其中的中文字元。

public class Test03 {
    public static void main(String[] args) {
        String str = "I am Chinese 我為武漢加油";
        String regex = "[\\u4e00-\\u9fa5]+";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        //必須先執行這條語句,否則直接執行matcher.group()會一直報錯
        boolean isFind = matcher.find();  
        if (isFind){  //建議先進行查找,如果找到了就取出找到的字元串,找不到的話執行.group會報錯
            String group = matcher.group();
            System.out.println("group = " + group);
        }
    }
}