代碼:正則表達式外卡的問題
strx = "exam/unwanted_tex/ple";
strx = strx.replace(/\/.+\//, '');
alert(strx); // Alerts "example"
2點簡單的問題:
- 此代碼替換中 「/」 和 「/」 一切嗎?
- 什麼不同之處是用 「*」 代替 「+」
代碼:正則表達式外卡的問題
strx = "exam/unwanted_tex/ple";
strx = strx.replace(/\/.+\//, '');
alert(strx); // Alerts "example"
2點簡單的問題:
是
'*'
和'+'
被稱爲量詞。 '*'
與之前的字符或組匹配零次或多次。從某種意義上說,這使匹配成爲可選的。 '+'
匹配一個或多個時間之前的字符或組。在你的例子中沒有實際的區別。但是,在其他應用中使用時,區別非常重要。這裏有一個例子:
'*'
量詞(匹配零次或多次)
// Match 'y' in Joey zero or more times
strx = "My name is Joe";
strx = strx.replace(/Joey*/, 'Jack');
alert(strx) // Alerts "My Name is Jack"
'+'
量詞(匹配一次或多次)
// Match 'y' in Joey one or more times
strx = "My name is Joe";
strx = strx.replace(/Joey+/, 'Jack');
alert(strx) // Alerts "My Name is Joe"
只是因爲你給了一個明確的例子,我會選擇你的答案'Jared Ng' – ajax333221
謝謝!正則表達式真的很酷的東西。如果你有興趣深入挖掘http://www.regular-expressions.info/。即使是基本的正則表達式知識也會帶來許多難以或無法實現的可能性。 –
.*
指:.
匹配任何單個字符,*
零次或多次,
.+
指: .
匹配任何單個字符,+
一次或多次
Mozilla的開發網絡是一個你最常見的JS參考資源。用它。 https://developer.mozilla.org/zh/JavaScript/Guide/Regular_Expressions –