Javascript Regex – 馬永占 譯

來源:互聯網
上載者:User

著作權聲明:原創作品,允許轉載,轉載時請務必以超連結形式標明文章原始出版、作者資訊和本聲明。否則將追究法律責任。http://blog.csdn.net/mayongzhan - 馬永占,myz,mayongzhan

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

我和Ronald討論Javascript和PHP的Regex.他過去一直用的是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)
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.