出處: https://www.hackerrank.com/challenges/js10-regexp-3/problem?isFullScreen=true
說明: 這題是使用 String.prototype.match() 的函式,來抓取符合條件的字串。
題目十分單純,就是給一個字串,找出裡面所有的數字。
範例
輸入: ‘102, 1948948 and 1.3 and 4.5’
輸出: [ ‘102’, ‘1948948’, ‘1’, ‘3’, ‘4’, ‘5’ ]
解法
這題完全只是考 match 的用法。
先看一下官方文件: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
其實也非常單純,以下是官網的範例:
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.'; const regex = /[A-Z]/g; const found = paragraph.match(regex); console.log(found); // expected output: Array ["T", "I"]
用字串去匹配 regx。
值得一題是關於 /g 的意義。 它是代表全域搜索的意思,如果沒有 /g ,會匹配第一個的詳細結果。
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.'; const regex = /[A-Z]/; const found = paragraph.match(regex); console.log(found); // expected output: ['T', index: 0, input: 'The quick brown fox jumps over the lazy dog. It barked.', groups: undefined]
以下是常用的 flag
Flag | Description |
---|---|
g | 全域搜索 |
i | 忽略大小寫 |
m | 多行搜索 |
回到題目
一個字串,匹配所有的阿拉伯數字,幾乎無難度可言:
const re = /[0-9]+/g // 或是寫成 const re = /\d+/g
簡寫說明可參照:解題 38. HackerRank > 10 Days of Javascript > Day 7: Regular Expressions II (表準表達式的 test 2)
到這邊,標準表達式的入門已經搞定了,有空再來多分享一些用標準表達式解題的案例吧。