1
2
|
java.util.regex.Pattern java.util.regex.Matcher |
1.Match
match 是從字符串最頭部開始匹配,一直到結束,需要匹配整個串
1
2
3
4
5
6
7
8
|
String content = "Welcome, bob!" ; content.match( "bob" ); //false content.match( ".*bob" ) //false content.match( ".*bob.*" ) //true String str= "test@yahoo.com.cn" ; Pattern pattern = Pattern.compile( "[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+" ,Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(str); boolean a = matcher.matches(); //匹配的時候返回true |
2.Find
1
2
3
4
5
|
boolean b = matcher.find(); //包含正則匹配的串為true // 找到所有匹配的串 while (matcher.find()) { String extracted = matcher.group( 0 ) } |
3.Replace
1
2
|
matcher.replaceFirst( "" ) matcher.replaceAll( "" ); |
4.Group
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
group( 0 ) 代表整個表達式 String line = "#星座運勢#20171013" ; String pattern = "\\#(\\p{L}*)\\#(\\d+)" ; //\p{L} 匹配 unicode any kind of letter from any language // 創建 Pattern 對象 Pattern r = Pattern.compile(pattern); // 現在創建 matcher 對象 Matcher m = r.matcher(line); if (m.find( )) { System.out.println( "Found value: " + m.group( 0 ) ); // "#星座運勢#20171013" System.out.println( "Found value: " + m.group( 1 ) ); // 星座運勢 System.out.println( "Found value: " + m.group( 2 ) ); // 20171013 } else { System.out.println( "NO MATCH" ); } |
總結
以上所述是小編給大家介紹的Java 正則表達式詳細使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/wangyayun/archive/2017/10/19/7692143.html