1. 程式人生 > >Java工具類之Pattern和Matcher(一)

Java工具類之Pattern和Matcher(一)

我們在web開發時,肯定會涉及到資料校驗,這時正則表示式就必須用到了。在Java中有個Pattern型別對某種正則表示式編譯,

,然後使用Matcher類進行判斷是否匹配等。其中String類中也有match();使用。這個對Pattern和Matcher的簡單使用。

package three.day.util.my;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringTs {


public static void main(String[] argv) throws IOException{
String regex = Pattern.quote("
[email protected]
");
System.out.println(regex);
Pattern pattern = Pattern.compile(regex);
CharSequence input = "[email protected]";
Matcher matchaer = pattern.matcher(input );
boolean suc = matchaer.matches();
System.out.println(suc);
System.out.println(pattern.flags());
}


private static void regex001() {
Pattern p = Pattern.compile("[a-zA-Z1-9]*@[a-zA-Z1-9]*.[a-zA-Z]*");
Matcher m = p.matcher("
[email protected]
");
boolean flag = m.matches();
System.out.println(flag);
}


private static void string002() {
String str = "中國";
System.out.println(str.charAt(0));
System.out.println(str.length());
char[] chs = new char[str.length()];
str.getChars(0, str.length(), chs, 0);
System.out.println(Arrays.toString(chs));
System.out.println(Arrays.toString(str.getBytes()));
}


private static void string001() throws UnsupportedEncodingException {
byte[] bytes = "中國".getBytes();
System.out.println(Arrays.toString(bytes));
String str3 = new String(bytes , "utf-8");
System.out.println(str3);
String str4 = new String(bytes , "gb2312");
System.out.println(str4);
String str5 = new String(bytes , "gbk");
System.out.println(str5);

System.out.println(str3.contentEquals(str4));
System.out.println(str3.equals(str4));

System.out.println(str3.contentEquals(str5));
System.out.println(str3.equals(str5));

System.out.println(str4.contentEquals(str5));
System.out.println(str4.equals(str5));

System.out.println(str3.compareTo(str4));
System.out.println(str3.compareTo(str4));

System.out.println(str3.compareTo(str5));
System.out.println(str3.compareTo(str5));

System.out.println(str4.compareTo(str5));
System.out.println(str4.compareTo(str5));
}
}