正则表达式测试方法

 1 var box=new RegExp('Box');    //第一个参数是模式字符串
 2 alert(box);     // /Box/两个反斜杠是正则表达式的字面量表示法
 3 
 4 
 5 var box=new RegExp('Box','gi');    //第二个参数可选,是模式修饰符
 6 alert(box);
 7 //模式修饰符的可选参数
 8 // i 忽略大小写
 9 // g 全局匹配
10 // m 多行匹配
11 
12 
13 var box=/Box/;    //使用字面量方式的正则
14 alert(box);
15 
16 
17 var box=/Box/gi;    //字面量正则,带修饰符的
18 alert(box);
19 
20 2、测试正则表达式
21 RegExp对象包含两个方法:test()和exec()。功能基本相似,用于测试字符串匹配。test()方法在字符串中查找是否存在指定的正则表达式兵返回布尔值,如果存在则返回true,不存在则返回false。exec()方法也用于在字符串中查找指定正则表达式,如果exec()方法执行成功,则返回包含该查找字符串的相关信息数组。如果执行失败,则返回null。
22 
23 
24 var pattern=new RegExp('Box');    //模式
25 var str='box';     //字符串
26 alert(pattern.test(str));     //返回的是false,大小写不一致
27 
28 
29 var pattern=new RegExp('Box','i');    //不区分大小写
30 var str='box';     //字符串
31 alert(pattern.test(str));     //返回的是true
32 
33 
34 var pattern=/Box/i;     //使用字面量的方式
35 var str='box';
36 alert(pattern.test(str));    //true
37 
38 
39 alert(/Box/i.test('box'));    //返回true,一句话匹配
40 
41 
42 var str1='box';
43 var str2='box';
44 alert(str1==str2);     //字符串的匹配比较方式
45 
46 
47 var pattern=/Box/i;    //不区分大小写匹配
48 var str='This is a box';    //一句英文
49 alert(pattern.test(str));    //字符串中是否包含模式中的正则
50 //This is a box 中是否包含不区分大小写的Box
51 
52 
53 
54 var pattern=/Box/i;
55 var str='box';
56 //alert(pattern.exec(str));
57 alert(typeof pattern.exec(str));    //返回的是数组,有就返回数组的值,没有就返回null
58 
59 
60 var pattern=/Box/i;
61 var str='saa';
62 alert(pattern.exec(str));    //如果没有匹配到就返回null
View Code

 

posted @ 2013-10-20 23:01  白小虫  阅读(607)  评论(0编辑  收藏  举报