欣迪

出處: 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

FlagDescription
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)

到這邊,標準表達式的入門已經搞定了,有空再來多分享一些用標準表達式解題的案例吧。

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。