http://www.cnblogs.com/dragon/archive/2006/05/08/394078.html
public class Test01 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// $表示尾端是xls
String a = "201008.xls";
String reg = "^2[0-9]{5}+\\.xls$";
System.out.println(a.matches(reg));
String reg1 = "About [cats] and dogs";
String b = "About cats and dogs";
System.out.println(b.matches(reg1));
String reg2 = "[0-9]{3}-?";
String b2 = "125";
String b22 = "125-";
System.out.println(b2.matches(reg2));
System.out.println(b22.matches(reg2));
String reg3 = "a[cats]c";
String b3 = "acc";
System.out.println(b3.matches(reg3));
String reg4 = "t.n";
String b4 = "tan";
System.out.println(b4.matches(reg4));
String reg5 = "tn";
String b5 = "tnfafaf";
System.out.println(b5.matches(reg5));
String reg6 = "a(c|a|t|s)c";
String b6 = "acc";
System.out.println(b6.matches(reg6));
String reg7 = "[^x]";
String b7 = "a";
System.out.println("b7=" + b7.matches(reg7));
String reg8 = "[a-z]+";
// String b8 = "3a";//false
String b8 = "ab";
System.out.println(b8.matches(reg8));
String reg9 = "[a-z]+ s + [0-9]{1,2}";
String b9 = "June 26";
System.out.println(b8.matches(reg9));
String string = "ayb";
// ^表示第二个字母不是a或b
String regString = "a[^ab]b";
System.out.println(string.matches(regString));
// *:匹配前一个字符0次或多次。+:匹配前一个字符1次或多次
// String b10 = "aaa"; //true
// String b10 = "";//true
String reg10 = "13a*";
String b10 = "13aaa";// false
System.out.println("b10=" + b10.matches(reg10));
// String reg11 = "ba*?";
String reg11 = "ba+?";
String b11 = "baaa";
System.out.println("b11=" + b11.matches(reg11));
//|表示或
String reg12 = "beijing|shanghai";
String b12 = "beijing";
// String b12 = "shanghai";//rue
System.out.println("b12=" + b12.matches(reg12));
//{n,m}:匹配前一个字符的至少n次最多m次的出现
String reg13 = "ab{2,5}c";
String b13 = "abbc";
System.out.println("b13=" + b13.matches(reg13));
// \d表示0-9 等同于[0-9];\D不在0-9范围内
String reg14 = "\\d";
String b14 = "2";
System.out.println("b14=" + b14.matches(reg14));
}
}
js demo:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
function val(){
var reg = "3[^ab]c";
var str = "3gc808";
var res = str.match(reg);
if(res!=null){
alert(str.match(reg)+" true");
return true;
}else return false;
}
<!--验证用户名是2-4位汉子-->
function checkForm(obj){
var username=obj.username.value;
var regx="^[\u4e00-\u9fa5]{2,4}$g"
if(!regx.test(username)){
alert("Invalid username!");
return false;
}
return true;
}
</script>
</head>
<body >
<form id="form" οnsubmit="return checkForm(this)">
<input type="text" name="username" />
<input type="submit" value="submit" />
</form>
</body>
</html>