Released 2023-03-30

Modified 2023-03-30

Tech

541Words (3min read)

利用正則表達式 Flag 提高搜索效率

Title Image

Photo by Kama on RegExr

前言 - Prologue

正則表達式是處理文本的強大工具,但在處理大量資料時,搜索效率可能會變得緩慢。為了提高正則表達式的搜索效率,可以使用不同的正則表達式 Flag 來控制其匹配行為。

正文 - Main text

正則表達式有下列幾種可選 Flags,允許全局或不區分大小寫的搜索。這些 Flags 可以單獨使用或以任何順序一起使用,並作為正則表達式的一部分包含在內。

i: 忽略大小寫

例如:使用 /hello/i 可以匹配 "Hello"、"HELLO"、"hello" 等。

g: 全局匹配

即不僅僅匹配第一個符合要求的字符串,而是匹配所有符合要求的字符串。

例如:使用 /a/g 可以匹配到 "abacad" 中所有的 "a"。

m: 多行匹配

在多行模式下,^$ 匹配的不再是整個文本的開頭和結尾,而是每行的開頭和結尾。

例如:使用 /^hello/m 可以匹配到 "hello" 出現在每行的開頭。

s: 特殊字符圓點匹配

即點(.)可以匹配包括換行符(\n)在內的任何字符。

u: Unicode 匹配

在 Unicode 模式下,正則表達式將按 Unicode 字符集進行匹配。

y: 粘性匹配

即匹配從上一次匹配位置開始的字符。

實例
  1. gi 和 ig: 全局匹配,並忽略大小寫
const text = "The quick brown fox jumps over the lazy dog";
const pattern = /the/gi;
const result = text.match(pattern);
console.log(result); // ["The", "the"]
  1. g: 全局匹配
const text = "cat bat sat fat";
const pattern = /at/g;
const result = text.match(pattern);
console.log(result); // ["at", "at", "at", "at"]
  1. gm 和 mg: 多行全局匹配
const text = "hello\nworld";
const pattern = /^h/gm;
const result = text.match(pattern);
console.log(result); // ["h"]
  1. u: Unicode 匹配
const text = "AπB";
const pattern = /\p{Letter}/gu;
const result = text.match(pattern);
console.log(result); // ["A", "π", "B"]

參考資料 - Reference

[1] 正規表達式 - JavaScript | MDN

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Regular_Expressions

[2] 正则表达式 – 修饰符(标记) | 菜鸟教程

https://www.runoob.com/regexp/regexp-flags.html

後記 - Epilogue

在找標題名稱怎麼取比較好時,發現了一個超級好的學習文章,分享一下!!

Flags - JavaScript RegExp | CodeGuage

真的非常詳細!!!

利用正則表達式 Flag 提高搜索效率

https:///en/blog/59

Author

Kama

Read more from Tech
lightbox-image
Toggle Button - Red Pandas Icons by svgrepo.com

Copyrights © 2023 Kama, All Rights Reserved.