简单正则表达式

<!doctype html>
<html>
    <head><meta>
        <title>Regex--正则简单demo</title>
    </head>
    <body>
    </body>
    <script>
 
 /*
 * demo1:
 *“\1”指与第一个()内的内容相同;
 */
 var a= /^<(\w+)\s*\/?>(?:<\/\1>)?$/ ;
 b1 = a.exec("<body>");
 b2 = a.exec("<br/>");
 b3 = a.exec("<div></div>");
 alert(b1);
 alert(b2);
 alert(b3);

 /*
 * demo2:
 *jquery源码中出现的正则的解读;
 */
   core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source;  //核心语句,.source获得正则的表达式;
  rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" );
  rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" );  //数字后不可直接跟‘px’;
  rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" );
  rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" )

//测试语句开始
  var n = "123dsga";
  alert(rnumsplit.exec(n));
  var m = "123pp";
  alert(rnumnonpx.exec(m));
  var a = "+=11.111";
  alert(rrelNum.exec(a));
  var b = "-=100%"; // b="100abc";
  alert(rfxnum.exec(b));

  /*
 * demo3:
 *jquery源码中出现的正则的解读;
 */
 //去除两边的空格;
     rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
  var a=" ad cd ";
  //alert('x'+a.replace(rtrim,'')+'x');
  //alert('x'+a+'x');
 
   /*
 * demo4:
 *jquery源码中出现的正则的解读;
 */
  // JSON RegExp
 rvalidchars = /^[\],:{}\s]*$/;
 rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
 rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g;
 rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g;    //"[^"\\\r\n]*" =>这部分不清楚;
 //测试语句开始
 var b = "\,:{}";
 alert(rvalidchars.exec(b));
 
 var c = "[add], [asdg]";
 alert(rvalidbraces.exec(c));
 
 var d='\\b';  //d='\\\/';  //d = "\\ua1aa";
 alert(rvalidescape.exec(d));
 
 var e='"n"';  //e='false';  //e ='1.1e-11';
 alert(rvalidtokens.exec(e)); 

匹配正数,正整数或正的浮点数(发票):
regExp:"^[1-9]\\d*.?\\d*$|^0.\\d*[1-9]\\d*$";

匹配正数,正整数或正的浮点数,保留两位小数(发票):
regExp:"^[1-9]\\d*(.\\d{1,2})?$|^0.(\\d){1,2}$";

匹配人名,chen/yi 或chen/yi lili (机票)
regExp:"^[a-zA-Z]+[\\/]([a-zA-Z])+([\\s]+[a-zA-Z]+)?$";

//未完,待续……
    </script>
</html>

相关推荐