java正則表達式匹配規(guī)則超詳細總結(jié)
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)文章
Spring?MVC?請求映射路徑的配置實現(xiàn)前后端交互
在Spring?MVC中,請求映射路徑是指與特定的請求處理方法關(guān)聯(lián)的URL路徑,這篇文章主要介紹了Spring?MVC?請求映射路徑的配置,實現(xiàn)前后端交互,需要的朋友可以參考下2023-09-09Java concurrency集合之CopyOnWriteArraySet_動力節(jié)點Java學(xué)院整理
CopyOnWriteArraySet基于CopyOnWriteArrayList實現(xiàn),其唯一的不同是在add時調(diào)用的是CopyOnWriteArrayList的addIfAbsent(若沒有則增加)方法2017-06-06springboot(thymeleaf)中th:field和th:value的區(qū)別及說明
這篇文章主要介紹了springboot(thymeleaf)中th:field和th:value的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10Java線程安全問題小結(jié)_動力節(jié)點Java學(xué)院整理
這篇文章主要介紹了Java線程安全問題小結(jié)的相關(guān)資料,需要的朋友可以參考下2017-05-05