欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java正則表達式匹配規(guī)則超詳細總結(jié)

 更新時間:2022年10月09日 10:16:42   作者:SmarTongs  
正則表達式并不僅限于某一種語言,但是在每種語言中有細微的差別,下面這篇文章主要給大家介紹了關(guān)于java正則表達式匹配規(guī)則的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下

1 單個字符的匹配規(guī)則如下:

2 多個字符的匹配規(guī)則如下:

3 復(fù)雜匹配規(guī)則主要有:

4 提取匹配的字符串子段

Pattern p = Pattern.compile("(\\d{3,4})\\-(\\d{7,8})");
Matcher m = p.matcher("010-12345678");

正則表達式用(...)分組可以通過Matcher對象快速提取子串:
- group(0)表示匹配的整個字符串;
- group(1)表示第1個子串,group(2)表示第2個子串,以此類推。

5 非貪婪匹配

用表達式

(\d+)(0*)

去匹配123000,10100,1001結(jié)果都是\d+匹配到所有字符而0*未用到,因為正則表達式默認采取貪婪匹配策略(匹配盡可能多的字符),在\d+后邊加個?就表示非貪婪(匹配盡可能少的字符),非貪婪如下:

(\d+?)(0*)

6 替換和搜索

6.1 分割字符串

對輸入的不規(guī)則字符串利用string.split()傳入正則表達式提取想要的部分:

"a b c".split("\\s"); // { "a", "b", "c" }
"a b  c".split("\\s"); // { "a", "b", "", "c" }
"a, b ;; c".split("[\\,\\;\\s]+"); // { "a", "b", "c" }

6.2 搜索字符串

public class Main {
    public static void main(String[] args) {
        String s = "the quick brown fox jumps over the lazy dog.";
        Pattern p = Pattern.compile("\\wo\\w");
        Matcher m = p.matcher(s);
        while (m.find()) {
            String sub = s.substring(m.start(), m.end());
            System.out.println(sub);
        }
    }
}

output:

row
fox
dog

6.3 替換字符串

使用正則表達式替換字符串可以直接調(diào)用String.replaceAll(),它的第一個參數(shù)是正則表達式,第二個參數(shù)是待替換的字符串。我們還是來看例子:

public class Main {
    public static void main(String[] args) {
        String s = "The     quick\t\t brown   fox  jumps   over the  lazy dog.";
        String r = s.replaceAll("\\s+", " ");
        System.out.println(r); // "The quick brown fox jumps over the lazy dog."
    }
}

6.4 反向引用

如果我們要把搜索到的指定字符串按規(guī)則替換,比如前后各加一個xxxx,這個時候,使用replaceAll()的時候,我們傳入的第二個參數(shù)可以使用$1、$2來反向引用匹配到的子串。例如:

public class Main {
    public static void main(String[] args) {
        String s = "the quick brown fox jumps over the lazy dog.";
        String r = s.replaceAll("\\s([a-z]{4})\\s", " <b>$1</b> ");
        System.out.println(r);
    }
}

output

the quick brown fox jumps <b>over</b> the <b>lazy</b> dog.

總結(jié) 

到此這篇關(guān)于java正則表達式匹配規(guī)則的文章就介紹到這了,更多相關(guān)java正則表達式匹配規(guī)則內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論