注意javascript中RegExp對象的test方法

來源:互聯網
上載者:User
對象

javascript 中的 RegExp 對象用於Regex相關的操作,這個對象提供了一個方法 test 來判定某個字串是否滿足某個 pattern. 傳回值是 true/false.
今天我碰到了一個問題:

<script type="text/javascript">
<!--
var re = /^\d+(?:\.\d)?$/ig;   

alert(re.test('112.3'));
alert(re.test('33'));
//-->
</script>
這裡兩個測試的字串應該都滿足Regex中的模式,返回 true. 可是測試結果卻依次是:true, false.

我估計問題的原因可能是因為 RegExp 對象是有狀態的,並且在 test 方法的執行時會在某個步驟中利用到狀態資訊,這樣就造成了錯誤。
(註:RegExp 全域對象有一些靜態屬性和方法,比如 RegExp.$1... RegExp$9, 等)

解決這個問題的辦法也很簡單,就是每次重新初始化一次Regex對象:

<script type="text/javascript">
<!--
alert(/^\d+(?:\.\d)?$/ig.test('112.3'));
alert(/^\d+(?:\.\d)?$/ig.test('33'));
//-->
</script>
在我看來,JavaScript 中Regex的這個行為設計的很奇怪,應該說是和正常使用習慣有那麼一點點的不同。雖然使用了很久的 JavaScript, 卻一直沒有注意到這個奇怪的現象。其他語言比如 Python, C# 等都不是這樣的。

瞭解這個問題詳細原因的朋友,請不吝指教。

posted on 2007-01-08 15:23 木野狐 閱讀(330) 評論(1)  編輯 收藏 引用 網摘 所屬分類: ASP,JS,CSS
 


Feedback
# re: 注意 JavaScript 中 RegExp 對象的 test 方法 2007-01-08 23:33 Derek
lastIndex Property See Also
RegExp Object Properties | Regular Expression Syntax

Applies To: RegExp Object
Requirements
Version 3
Returns the character position where the next match begins in a searched string.

RegExp.lastIndex
The object associated with this property is always the global RegExp object.

Remarks
The lastIndex property is zero-based, that is, the index of the first character is zero. Its initial value is –1. Its value is modified whenever a successful match is made.

The lastIndex property is modified by the exec and test methods of the RegExp object, and the match, replace, and split methods of the String object.

The following rules apply to values of lastIndex:

If there is no match, lastIndex is set to -1.
If lastIndex is greater than the length of the string, test and exec fail and lastIndex is set to -1.
If lastIndex is equal to the length of the string, the regular expression matches if the pattern matches the empty string. Otherwise, the match fails and lastIndex is reset to -1.
Otherwise, lastIndex is set to the next position following the most recent match.

http://www.cnblogs.com/RChen/archive/2007/01/08/regexp_test.html



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.