Javascript 正则表达式 - 马永占 译

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出版、作者信息和本声明。否则将追究法律责任。http://blog.csdn.net/mayongzhan - 马永占,myz,mayongzhan

原文地址:http://www.thespanner.co.uk/2008/02/01/javascript-regular-expressions/

我和Ronald讨论Javascript和PHP的正则表达式.他过去一直用的是PHP的preg,对Javascript的正则比较陌生,所以我就分享了我的script知识.

首先,PHP中的preg_match和Javascript中的match有相同的功能,他们除了语法之外其他的都非常相似.在Javascript中match是字符串对象(就是一个字符串)的一部分,下面是match的用法:



alert('Test'.match(/[a-z]/))



你也可以把match用在子正则匹配上,如下(我尽量把这些写的类似于PHP):-



pattern = /([a-z]+)([0-9]+)([A-Z]+)/;
subject = 'test1234TEST';
matches = subject.match(pattern);
match1 = matches[1];
match2 = matches[2];
match3 = matches[3];
alert(match1);
alert(match2);
alert(match3);



你也可以用RegExp创建匹配式,这样有利于传递变量到匹配式中,而且不需要"//"



a = 'a+';
alert(new RegExp(a).exec('123aaaabcdef'));



exec方法也可以被"//"这样的匹配式使用.



alert((/[0-9]+/).exec('12345abcdef'))



Javascript支持像"g","i"和"m"的修正符,如下:



matches = 'ababababababa'.match(/[a]/g);
alert



修改 by Planet PHP, 更多: the original (4722 bytes)







Ronald and I had a good conversation about Javascript regular expressions comparing them to PHP. He was having difficultly with the syntax because he was used to preg in PHP so I promised to share my knowledge gained from developing various online scripts.
First up preg_match in PHP can be achieved using the match function in Javascript, they are both very similar but it’s just a matter of getting your head round the different syntax. Match is part of the String object and here is how to use it:-
alert('Test'.match(/[a-z]/))
You can match subpatterns like this (I’ve tried to keep it close to PHP syntax as possible):-
pattern = /([a-z]+)([0-9]+)([A-Z]+)/;
subject = 'test1234TEST';
matches = subject.match(pattern);
match1 = matches[1];
match2 = matches[2];
match3 = matches[3];
alert(match1);
alert(match2);
alert(match3);
You can also create matches using the RegExp object, this is useful for passing variables into the pattern which to my knowledge isn’t possible with “//” syntax.
a = 'a+';
alert(new RegExp(a).exec('123aaaabcdef'));
The exec method can also be called from “//” patterns.
alert((/[0-9]+/).exec('12345abcdef'))
Javascript supports the modifiers “g”, “i” and “m”, here’s how to use them with “//” syntax:-
matches = 'ababababababa'.match(/[a]/g);
alert
Truncated by Planet PHP, read more at the original (another 4722 bytes)

你可能感兴趣的:(JavaScript,PHP,正则表达式,UP,出版)