`RegExp` 物件
本文將說明 RegExp 物件。
我們將透過實際範例說明 RegExp 物件。
YouTube Video
RegExp 物件
什麼是 RegExp?
RegExp(正規表示式)是用來描述字串樣式的物件。與簡單的字元比較不同,您可以靈活地定義「符合特定條件的字串」。
透過使用 RegExp 物件,您可以簡潔明瞭地執行搜尋、驗證、擷取及替換字串等操作。這對於日常的表單輸入驗證、日誌分析、以及文字格式化等任務非常有效。以下是一些正則表達式的簡單範例。
1const pattern = /abc/;- 這個正規表示式會檢查字串中是否包含 'abc'。
建立正規表示式的方法(兩種方式)
RegExp 語法有兩種類型:字面量表示法 和 建構子表示法。
1// Literal notation: pattern and flags are written together
2const literal = /hello/;
3const literalWithFlag = /hello/i;
4const literalDigits = /\d+/;
5
6// Constructor notation: pattern and flags are passed separately
7const constructor = new RegExp("hello");
8const constructorWithFlag = new RegExp("hello", "i");
9const constructorDigits = new RegExp("\\d+");- 字面量表示法簡潔且易讀,適合用於作為常數的正則表達式。。另一方面,當你想要使用變數構建模式或於執行時決定內容時,則使用建構函數表示法。
- 使用字面量表示法時,可以直觀地同時描述正則表達式及其標誌。相對的,若使用建構函數表示法,則需要分開指定模式和標誌。
- 此外,當使用建構函數表示法時,需要將正則表達式作為字串傳遞,因此反斜線必須轉義兩次。
test():最基本的驗證方法
RegExp 物件提供了使用正則表達式進行判斷和操作的方法。test() 方法會回傳 pattern 是否符合的布林值。
1const regex = /JavaScript/;
2
3console.log(regex.test("I love JavaScript")); // true
4console.log(regex.test("I love TypeScript")); // false
- 這是最先應該學會的方法,適合用於條件判斷或輸入驗證。
match():取得配對結果
match() 會回傳包含匹配字串及詳細資訊的陣列。
1const text = "Version 1.2.3";
2const result = text.match(/\d+\.\d+\.\d+/);
3
4console.log(result[0]); // "1.2.3"
match()在提取和分析資料時,比test()更方便。
replace():運用正規表示式取代
replace() 會將符合條件的部分轉換成其他字串。
1const text = "Hello World";
2const result = text.replace(/\s+/g, " ");
3
4console.log(result); // "Hello World"
- 您可以用它來進行日誌格式化或去除不必要的空白字元。
旗標基礎(g, i, m)
您可以在正則表達式中指定「標誌(flags)」。標誌是控制正則表達式根據特定規則處理字串的選項。即使是相同的模式,根據標誌的不同,結果也會改變。
1const text = "apple Apple APPLE";
2const regex = /apple/gi; // or new RegExp("apple", "gi");
3
4console.log(text.match(regex)); // ["apple", "Apple", "APPLE"]
g(全域)標誌會在整個字串中搜尋。i(忽略大小寫)標誌在匹配時會忽略大小寫的差異。
1const multilineText = `apple
2banana
3apple`;
4
5const regexM = /^apple/gm;
6
7console.log(multilineText.match(regexM)); // ["apple", "apple"]
m(多行)標誌用於將多行字串視為逐行處理。有了這個,^及$會依每一行的開頭或結尾運作,而不是整個字串。
字元類別:合併多個選項
利用中括號 [],你可以為某個字元位置定義多個候選字元。
1const regex = /gr[ae]y/;
2
3console.log(regex.test("gray")); // true
4console.log(regex.test("grey")); // true
- 這有助於處理拼字不同或簡單的選項替換。
元字元:常用簡化語法
元字元是允許你以簡短形式撰寫常用模式的符號。
1const regex = /\d{4}-\d{2}-\d{2}/; // or new RegExp("\\d{4}-\\d{2}-\\d{2}");
2
3console.log(regex.test("2025-12-29")); // true
\d代表數字,{n}則指定重複次數。
^ 和 $:驗證整個字串
^ 和 $ 分別代表字串的起始與結尾。
1const regex = /^\d+$/;
2
3console.log(regex.test("123")); // true
4console.log(regex.test("123a")); // false
- 這在需要完全吻合的情況(如表單輸入驗證)時很重要。
分組與捕捉
使用括號 (),您可以提取部分值。
1const text = "2025/12/29";
2const regex = /(\d{4})\/(\d{2})\/(\d{2})/;
3const [, year, month, day] = text.match(regex);
4
5console.log(year, month, day); // 2025 12 29
- 常用來解析日期與結構化的字串。
常見錯誤與注意事項
正規表示式雖強大,但很容易變得難以閱讀。
1// Hard to read
2const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+$/;- 如果變得太複雜,您可以考慮加入註解、分割表達式或重新檢討整個處理流程。
總結
RegExp 是 JavaScript 中簡單且精確描述字串運算不可或缺的基礎功能。你不需要一開始就學會複雜的正則規則;根據需求活用如 test、match、replace 等基礎語法才是最重要的。如果你能把正規表示式當作『模式管理工具』,而不是『特殊知識』,將大幅提升輸入驗證或文字處理的品質與可讀性。
您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。