> For the complete documentation index, see [llms.txt](https://hannahpun.gitbook.io/leetcode-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hannahpun.gitbook.io/leetcode-note/tools/regex.md).

# Regex

<pre class="language-javascript"><code class="lang-javascript"><strong>// 以下兩個相同
</strong><strong>var re = new RegExp("\\w+", "gi");
</strong>var re = /\w+/gi;
</code></pre>

[RegexOne](https://regexone.com/)

```
/g // global 抓
/i // 代表不區分大小寫都找
```

* **\[abc]** → 抓單一個字元: a, b, or c

* **\[^abc]** → 抓任何單一字元除了 a, b, or c

* **\[a-z]** → 抓任何小寫a-z之間的字元

* **\[a-zA-Z]** → 抓任何小寫a-z,大寫A-Z之間字元

* **\d** → 任何數字字元

* **\D** → 任何不是數字字元

* **\w** → 任何字串+底線，其實等於\[a-z\dA-Z\_]

* **\W** → 跟\w相反

* **\s** → 空白鍵

* **\S** → 任何不是空白鍵字元

* **.** → 任何字串

* **\\.** → .這個符號

* **^** → 字串開頭位置

* **$** → 字串結尾位置

* **\b** → boundary.  "**one** 2sa **one**".match(/\bone\b/g)

* (…) → 抓()裡面的字串

* **a|b** → a 或 b, 它可以是一串字串

* **\b** → 在邊界的字元, ex hello.pdf, h跟p都是邊界字元

* **a?** → 抓**0個或1個的a , ex 我想抓a跟(a), /(?a/)?**

* **a\*** → 抓0以上的a, ex 抓hello全部, (\w\*)

* **a+** → 抓1以上的a

* **a{3}** → 抓3個a

* **a{3,}** → 抓3個以上a

* **a{3,6}** → 抓3-6個之間的a

**email:  (\[\w\\-]+@\[\w\\.]+)**

* \[\w\\-] → 抓任何單一字元跟-  // h,a,n,n,a,h
* \[\w\\-]+ → 抓成字串 // hannah
* (\[\w\\-]+@\[\w\\.]+) → 把email整個包起來抓

**phone: \\(?\d{3}\\)?\[\s\\-]\d{3}\[\\-\s]\d{4}**

* \d{3} → 3個數字 // 111
* \\(?\d{3}\\)? →  3個數字可以被()包起來也可以不要 // 111 or (111)
* \\(?\d{3}\\)?\[\s\\-] →  3個數字後可能會是-或空格隔開 // 111-, 111
* \\(?\d{3}\\)?\[\s\\-]\d{3} → 再接3個數字 // 111-222
* \\(?\d{3}\\)?\[\s\\-]\d{3}\[\\-\s] → 後面可能會是-或空格隔開 // 111-222-, 111-222
* \\(?\d{3}\\)?\[\s\\-]\d{3}\[\\-\s]\d{4} →  最後再接4個數字 // 111-222-3333
