本文為大家分享了如何運用java正則表達式的方法,供大家參考,具體內容如下
1.是否匹配給定的模型
代碼如下:
1
2
3
4
5
6
7
8
9
|
public static void main(string[] args) { string pattern= "a\\d{2}f" ; //模型:以a開始,接2位數字,以f結尾 string s= "a22" ; boolean b=s.matches(pattern); system.out.println(s+ "匹配" +pattern+ "嗎:" +b); s= "a22f" ; b=s.matches(pattern); system.out.println(s+ "匹配" +pattern+ "嗎:" +b); } |
運行結果如下:
2.替換
代碼如下:
1
2
3
4
5
6
7
|
public static void main(string[] args) { string s= "你你 好 嗎嗎嗎 " ; system.out.println( "替換前:" +s); string pattern= "\\s+" ; s=s.replaceall(pattern, "" ); system.out.println( "替換后:" +s); } |
運行結果如下:
3.去重
代碼如下:
1
2
3
4
5
6
7
|
public static void main(string[] args) { string s= "你你好嗎嗎嗎" ; system.out.println( "替換前:" +s); string pattern= "(.)\\1+" ; s=s.replaceall(pattern, "$1" ); system.out.println( "替換后:" +s); } |
運行結果如下:
PS:服務器之家推薦兩款實用的在線正則表達式工具
正則表達式在線測試工具 https://tool.zzvips.com/t/regex/
正則表達式生成器 https://tool.zzvips.com/t/regcode/
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_41815326/article/details/81154121