日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Codewars-Javascript训练手册:正则表达式(Regular Expressions)

發布時間:2025/3/20 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Codewars-Javascript训练手册:正则表达式(Regular Expressions) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Autocomplete! Yay!(字符串自動補全)

The autocomplete function will take in an input string and a dictionary array and return the values from the dictionary that start with the input string. If there are more than 5 matches, restrict your output to the first 5 results. If there are no matches, return an empty array.(autocomplete 函數輸入一個字符串和字典數組,返回開頭是該字符串的值,返回值的個數最多限制為5個,無匹配則返回空數組)
對于輸入字符串的要求:Any input that is NOT a letter should be treated as if it is not there. For example, an input of “$%^” should be treated as “” and an input of “ab*&1cd” should be treated as “abcd”.

Example:

autocomplete('ai', ['airplane','airport','apple','ball']) = ['airplane','airport']

初始解決方案:

function autocomplete(input, dictionary){var str = input.replace(/[^A-Za-z]+/g,'');var pattern = new RegExp('^'+str,'i');var temp = dictionary.filter(function(value){if(pattern.test(value)){return true;}else{return false;}});return temp.length<6?temp:temp.slice(0,5); }

知識點:創建一個正則表達式有兩種方式,一是直接量語法var reg = /pattern/ 適用于正常輸入的正則表達式,二是創建 RegExp 對象,語法是new RegExp(pattern, attributes);例如:var reg = new RegExp('pattern','gi') 第二種語法適用于對正則表達式的拼接。注意第一種語法直接輸入正則的內容即可,解釋器通過/×××/ 這樣的形式確認類型為RegExp對象。而第二種語法則類似字符串的寫法。
優化代碼:

//正則表達式的變量pattern可以簡寫為: var pattern = new RegExp('^'+input.replace(/[^A-Za-z]+/g,''),'i') //Array的slice語法中的第二個參數可以大于Array的長度,對輸出無影響,例: var tt = ['a','b']; console.log(tt.slice(0,5));//輸出為 ["a", "b"] //因此可以簡化最后一步的判斷輸出結果是否超過5個值return dictionary.filter(function(w){ return r.test(w); }).slice(0, 5);

所以,最簡的代碼是:

function autocomplete(input, dictionary){var r = new RegExp('^' + input.replace(/[^a-z]/gi,''), 'i');return dictionary.filter(function(w){ return r.test(w); }).slice(0, 5); }

這正是Codewars上得票最高的答案。

Credit Card Mask(信用卡字符加密)

給出一個函數maskify用“#”字符替換超過4個字符的字符串,4個字符則返回自身。例如:

maskify("4556364607935616") == "############5616" maskify( "64607935616") == "#######5616" maskify( "1") == "1" maskify( "") == ""

本以為可以用一個正則表達式可以解決問題,然而發現RegExp {X} 量詞中x必須為數字。于是將原字符串分割開進行匹配,代碼如下:

function maskify(cc) { var len = cc.length; if(len<5){return cc; }else{ //對字符串分割后進行正則匹配return cc.slice(0,len-4).replace(/\w/g,'#') + cc.slice(len-4); } }

然而,我忘了正則的另外一個用法:/regexp(?=n)/ ?=n 量詞匹配任何其后緊接指定字符串 n 的字符串,但匹配的內容并不包括指定字符串n。
所以,Codewars最簡短的代碼正是如此:

function maskify(cc) {return cc.replace(/.(?=....)/g, '#');//也可寫出cc.replace(/.(?=.{4})/g, '#') }

轉載于:https://www.cnblogs.com/xihe/p/6138615.html

總結

以上是生活随笔為你收集整理的Codewars-Javascript训练手册:正则表达式(Regular Expressions)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。