Javascript 正则表达式 - 马永占 译

本文对比了JavaScript和PHP中的正则表达式的使用方法,详细介绍了如何在JavaScript中使用match和exec方法,并提供了实例说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出版、作者信息和本声明。否则将追究法律责任。http://blog.youkuaiyun.com/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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值