對象
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