原始題目如下:(6kyu)
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.
翻譯:
字串中每一個單字會包含1~9的數字,按照1~9順序,重新排列單字組合完成正確的句子。
範例:
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
"" --> ""
function order(words){
var reg=new RegExp('[0-9]+')
return words.split(' ').sort((a,b)=>a.match(reg)-b.match(reg)).join(' ')
}
字串要做陣列進階的處理,一樣是先使用的split()切割字串。sort()中compare function要傳入排序依據,match(reg)回傳1~9中符合哪個數字的結果,以match出的數字當作排序依據,並直接改變words陣列的排列!
在前面的Find the smallest integer in the array有稍微提到sort()的使用。
function order(words){
return words.split(' ').sort(function(a, b){
return a.match(/\d/) - b.match(/\d/);
}).join(' ');
}
解法差不多一樣是使用regex去sort!
基本用法: (以下正規表示式省略頭尾的 //)
| 正規表示式 | 說明 | 成立字串 | 不成立字串 |
|---|---|---|---|
| a | 包含a的字串 | ab,cba | xyz |
| ^a | 以a開頭的字串 |
ab,abc | bca |
| a$ | 以a結尾的字串 |
qwea,reda | ased,adde |
| [123] | 包含1 or 2 or 3的字串 | as3,fv2 | as4 |
| [0-9] | 包含數字的字串 | This1, Th1is | this |
| [a-z0-9] | 包含數字或小寫字母的字串 |
job work 4love | !@# |
| [^0-9] | 不含數字的字串 |
mom, dad | 4love |
跳脫特定字元:(以下正規表示式省略頭尾的 //)
| 正規表示式 | 說明 |
|---|---|
| \d | 任意數字,等同於[0-9] |
| \D | 任意非數字字元,等同於 [^0-9] |
| \w | 所有文字 |
| \W | 所有非文字字元,標點符號或特殊字元 |
| \s | 空白字元 |
| \S | 非空白字元 |
匹配次數
| 正規表示式 | 說明 |
|---|---|
| /a?/ | 0或1個a |
| /a+/ | 至少1個a |
| /a*/ | 0或多個a(任意~) |
| /a{4}/ | 四個a |
regex不用時,很容易忘,網路有很多檢測的網站可以使用。
Ex:自己比較常用regex101
通常這類型的網站會幫忙把匹配的字元反白外,還會有文字解釋你輸入的正規表示式。
圖摘自regex101
另外推推RegexOne也很適合拿來學習正規表示法,有分成Lesson和Problem的單元,每一個單元都有一個主題,吸收完文字說明後,還有底下的練習可以當驗收!
以上為今日分享的內容,若有錯誤或是建議,請再隨時和我聯繫。