一,java.util.regex包中提供了兩個類來表示對正則表達式的支持1.Matcher,通過解釋Pattern對character sequence 執行匹配操作的引擎public final class Matcher implements MatchResult2.Pattern,正則表達...
一,java.util.regex包中提供了兩個類來表示對正則表達式的支持
1.Matcher,通過解釋Pattern對character sequence 執行匹配操作的引擎
public final class Matcher implements MatchResult
2.Pattern,正則表達式的編譯表示形式
public final class Pattern implements java.io.Serializable
代碼:
package yuki.regular; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FirstTest { public static void main(String[] args) { /** * Pattern,正則表達式的編譯表示形式 * public final class Pattern implements java.io.Serializable */ String str = "hi! i am a tony; glad to see you!"; String regex = "\\p{Punct}"; Pattern pattern = Pattern.compile(regex); String[] strArr = pattern.split(str); for(int i = 0; i < strArr.length; ++i) System.out.println("strArr[" + i + "] = " + strArr[i]); /** * Matcher,通過解釋Pattern對character sequence執行匹配操作 * public final class Matcher implements MatchResult */ Matcher matcher = pattern.matcher(str); System.out.println(matcher.matches() ? "匹配" : "不匹配"); System.out.println( Pattern.compile("\\p{Punct}+").matcher(".,.;").matches() ? "匹配" : "不匹配"); String s2 = "[email protected]"; Pattern p2 = Pattern.compile("\\w+@\\w+.[a-zA-Z]+"); Matcher m2 = p2.matcher(s2); System.out.println("m2.matches() = " + m2.matches()); } }
運行結果:
1 2 3 4 5 6 |
strArr[0] = hi
strArr[1] = i am a tony
strArr[2] = glad to see you
不匹配
匹配
m2.matches() = true
|
二,String類對正則的支持
代碼:
package yuki.regular; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SecondTest { public static void main(String[] args) { /** * 匹配替換 */ String date = "2015/2/27"; Pattern p = Pattern.compile("/"); Matcher m = p.matcher(date); String s = m.replaceAll("-"); System.out.println("m.matches() = " + m.matches()); System.out.println("s = " + s); System.out.println("m.replaceFirst(\"-\") = " + m.replaceFirst("-")); //匹配電話號碼 String phone = "0755-28792686"; String regex = "\\d{3,4}-\\d{7,8}"; boolean isPhone = phone.matches(regex); System.out.println("isPhone = " + isPhone); } }
運行結果:
1 2 3 4 |
m.matches() = false
s = 2015-2-27
m.replaceFirst( "-" ) = 2015-2/27
isPhone = true
|
三,常用示例
代碼:
package yuki.regular; public class ThirdTest { public static void main(String[] args) { /** * 至少含有字元串數組中的一個 */ String s = "123,456,789,012,345"; String s2 = "123,456,789,013,345"; String regex = ".*(234|678|012).*"; boolean isMatch = s.matches(regex); boolean isMatch2 = s2.matches(regex); System.out.println("isMatch = " + isMatch); System.out.println("isMatch2 = " + isMatch2); //匹配金額 String price = "499.00"; System.out.println("price.matches(\"\\d+.\\d+\")" + price.matches("\\d+.\\d+")); } }
運行結果:
1 2 3 |
isMatch = true
isMatch2 = false
price.matches( "\d+.\d+" ) true
|