- 论坛徽章:
- 0
|
/*
* Created on 2006-4-10
*(c)castit.com.cn
*/
package samples;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author zhulieping
*该类主要是用来描述并在java中练习使用正则表达式
*/
public class Sample_6_Reg {
/**
* 校验一个字符串str是否与regExp格式匹配
* @param str
* @param regExp
* @return
*/
public static boolean validate(String str,String regExp){
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(str);
System.out.print("'"+str+"'"+"匹配"+"'"+regExp+"'"+" :");
return matcher.find();
}
public static void main(String args[])
{
String str="6,'',0,0,9,'1999/12/31'";
String strReg="^\\d+,'.*',0|1,0|1,\\d+,'\\d{4}/\\d{2}/\\d{2}'$";
String strBook="4,'The Art of Peter Max',4,4,1,0,'2000/12/31'";
String strBookReg="^\\d+,'.*',\\d+,\\d+,0|1,0|1,'\\d{4}/\\d{2}/\\d{2}'$";
//匹配字符串格式
System.out.println(Sample_6_Reg.validate(str,strReg));
//与指定字符集[aeiou]中的任何单个字符匹配
System.out.println(Sample_6_Reg.validate("nihao","[aeiou]"));
//不与指定字符集[aeiou]中的任何单个字符匹配ps:只要有一个字符不匹配即认为匹配成功
System.out.println(Sample_6_Reg.validate("nihao","[^aeiou]"));
//与指定字符集[a-eA-E]中区间中的任何单个字符匹配,并要求字符串是先字符后数字,缺一不可
System.out.println(Sample_6_Reg.validate("ni hao2","[a-eA-E]\\d++"));
//与任何单词字符匹配(英文)
System.out.println(Sample_6_Reg.validate("你好","\\w"));
//与任何非单词字符匹配
System.out.println(Sample_6_Reg.validate("你好","[\\p{Nd}]"));
//与任何空白字符匹配
System.out.println(Sample_6_Reg.validate("@ni hao","\\s"));
//与任何十进制数匹配,d{5}中5表示连续5个十进制数
System.out.println(Sample_6_Reg.validate("123n45nihao","\\d{5}"));
//匹配5个英文字母,\\w*,\\(abc)*....
System.out.println(Sample_6_Reg.validate("ni好hao","\\w{5}"));
//匹配字符串abc,但是匹配数量不能超过3个。不能少于2两个
System.out.println(Sample_6_Reg.validate("你好","\\W{0,1}"));
//匹配字符,要求字符串必须小写或者空格
System.out.println(Sample_6_Reg.validate("nihao ","[\\p{Lower}\\s]{5}"));
//'^':指定匹配必须出现在字符串的开头或者行的开头,同时匹配"ni"
System.out.println(Sample_6_Reg.validate("nhaoni","^ni"));
//$:指定匹配必须出现在以下位置:字符串结尾,字符串结尾的\n之前或者行的结尾
System.out.println(Sample_6_Reg.validate("nihao","$"));
//验证输入字符是否全部为英文字母
System.out.println(Sample_6_Reg.validate("nhaoni你好","^\\w+$"));
//验证字符串是否是电子邮件格式
System.out.println(Sample_6_Reg.validate("kunanfo@163.com你好","^\\w+@\\w+\\.[(com){org}]+$"));
//替换由(?<name>)组匹配的最后一个字符串,分组
//System.out.println(Sample_6_Reg.validate("2004/5/2","^\\b(?<year>\\d{2,4})/(?<month>\\d{1,2})/(?<day>\\d{1,2})\\b"));
//符合两种条件的都成立,纯字符串或者纯数字串
System.out.println(Sample_6_Reg.validate("12r45","^[0-9]*$|^[a-zA-Z]*$"));
//得到不以数字开头的字符组合(?=),(?<=19)99,\\b(?!un)\\w+\\b
System.out.println(Sample_6_Reg.validate("12nihao","^(?<![0-9])[a-zA-Z]{2,}"));
//得到以数字开头的字符组合
System.out.println(Sample_6_Reg.validate("1nihao","^[0-9][a-zA-Z]+$"));
//得到不以数字结尾的字符组合为什么nihao7需要结束符号$,而nihao8却不需要?
System.out.println(Sample_6_Reg.validate("nihao7","^[a-zA-Z]+(?!\\d)$"));
//得到以数字结尾的字符组合
System.out.println(Sample_6_Reg.validate("nihao8","^[a-zA-Z]+(?=\\d)"));
//不允许ab同时出现
System.out.println(Sample_6_Reg.validate("nihaoaacbc","^(?!.*?ab.*).*$"));
System.out.println(Sample_6_Reg.validate(strBook,strBookReg));
}
} |
|