2013年1月5日星期六

JavaScript正则表达式定义常用方法

正则的定义:


  • var reg = /pattern/igm;

  • var reg = new RegExp('pattern', 'igm');



1、其中i的意思是忽略大小写,如:


不加i


reg = /test/;

str = 'tEStab';

reg.exec(str);//返回null


加上i

reg = /test/i;

str = "tEStab";

reg.exec(str);//返回["tESt"]


2、 g的意思是全局查找,


不加g

reg = /tes[ta]/;

str = 'testatesab';

reg.exec(str); //返回["test"]

reg.exec(str); //返回["test"]

加上g

reg = /tes[ta]/g;

str = 'testatesab';

reg.exec(str); //返回["test"]

reg.exec(str); //返回["tesa"]

reg.exec(str); //返回null

3、m的意思是指让^和$匹配行首和行尾


不加m

reg = /^b[ac]/g;

str='ba.sin\nbcsohu';

reg.exec(str); //返回["ba"]

reg.exec(str); //返回null



加上m
reg = /^b[ac]/g;



str='ba.sin\nbcsohu';
reg.exec(str); //返回["ba"]

reg.exec(str); //返回["bc"]
reg.exec(str); //返回null





正则的常用方法:

1、exec方法


  • result = reg.exec(str)



返回的result是一个类数组的对象,如果在chrome的console里看到是数组,其实使用for in可以得到另外两个只读属性index, input



for(a in result) console.log(a + ":" + result[a]);

0:tESt

index:0

input:tEStab



result.input存放匹配的原始字符串,result.index是当前匹配的索引,其作用是当我们使用了g修饰符时,它是多次执行reg.exec(str)的依据;数据里依次存放匹配到的字符串,和正则中小括号匹配的分组数据,如:



reg = /tes(t)/;

str = 'testab';

reg.exec(str);//返回["test", "t"]


exec方法也同样影响RegExp(稍后介绍)

2、test方法



  • reg.test(str)



测试是否匹配成功,若成功返回true,否则返回false。跟exec一样,其也返回结果,存放在RegExp.$*几个变量中,其中RegExp.$input, RegExp.$_表示输入字符串,而RegExp.$1 - RegExp.$9表示匹配的变量

3、RegExp对象

如果直接使用console.log(RegExp),function RegExp() { [native code] },这也是正则的构成方法,使用for in来看一下其中的变量:
reg = /tes(t)/;
str = 'atestb';
reg.exec(str);//结果为 ["test']
for(name in RegExp) console.log(name + ":" + RegExp[name]);


input:atestb

multiline:false

lastMatch:test

lastParen:t

leftContext:a

rightContext:b

$1:t

$2:

$3:

$4:

$5:

$6:

$7:

$8:

$9:


其中RegExp.input = RegExp.$input = RegExp.$_,RegExp.multiline表示m标签符是否被设置

当然,能用正则的方法还有String对象的match, replace, split, search等方法,有时间再做一次介绍。这里只是介绍其使用方法,对于如果写正则表达式没有深入讲,内容还有很多

推荐阅读:JavaScript正则表达式