> For the complete documentation index, see [llms.txt](https://docs.webmix.cc/javascript/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.webmix.cc/javascript/4.-javascript-chang-yong-nei-jian-han-shi/4.7-regular-expression.md).

# 4.7 正規表達式(Regular Expression)

在 `javascript/practice` 資料夾下，建立 `regular_expression.html` 檔案，以便練習。

## 使用方式

### 驗證

* 定義一個字串的規則格式：寫法為 `/正規表示式/`。
* 再使用 `.test()` 方法，來驗證給定的字串是否符合規則，是的話回傳 `true`，反之回傳 `false`。

例：

```javascript
// 定義一個比對的規則，以下的 \s{1} 表示僅能有1個空格。
var pattern = /the\s{1}book/;
// 或以下這個寫法：
//var pattern = new RegExp(/the\s{1}book/);


// 以下是想要比對的字串
var str = "the book";
//var str = "The book";

alert(pattern.test(str));
```

延續上例，若希望不區分大小寫，就將：

```javascript
var pattern = /the\s{1}book/;
```

改成：

```javascript
var pattern = /the\s{1}book/i; // i 是 ignore(忽略) 的意思。
// 或
// var pattern = new RegExp(/the\s{1}book/, "i");
```

### 取代

有分大小寫：

```javascript
var str = "visit abc and def and abc";
var new_str = str.replace(/ABC/, "101"); // 找不到

console.log(new_str); // visit abc and def and abc
```

希望不分大小寫(但只會取代找到的第一個)：

```javascript
var str = "visit abc and def and abc";
var new_str = str.replace(/ABC/i, "101");

console.log(new_str); // visit 101 and def and abc
```

全部搜尋取代，且不分大小寫：

```javascript
var str = "visit abc and def and abc";
var new_str = str.replace(/ABC/ig, "101");

console.log(new_str); // visit 101 and def and 101
```

## 特殊字元列表

| 字元          | 比對規則                                                            | 範例                                                                                    |
| ----------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| **^**       | 字串起始                                                            | **/^This/** 與 "**This is**" 比對結果：**true**。                                            |
| **$**       | 字串結尾                                                            | **/end$/** 與 "**the end**" 比對結果：**true**。                                             |
| **\***      | 出現零次或多次                                                         | **/se\*/** 與 "**seeee**"、"**se**" 比對結果：**true**。                                      |
| **?**       | 出現零次或 1 次                                                       | **/ap?/** 與 "**apple**"、"**and**" 比對結果：**true**。                                     |
| **+**       | 出現 1 次以上                                                        | **/ap+/** 與 "**apple**" 比對結果：**true**。與 "**and**" 比對結果：**false**。                     |
| **{n}**    | 剛好出現 n 次                                                        | **/ap{2}/** 與 "**apple**" 比對結果：**true**。與 "**and**" 比對結果：**false**。                   |
| **{n,}**    | 至少出現 n 次                                                        | **/ap{2,}/** 與 "**apple**"、"**appple**" 比對結果：**true**。與 "**aple**" 比對結果：**false**。   |
| **{n,m}**   | 最少出現 n 次，最多出現 m 次                                               | **/ap{2,4}/** 與 "**apple**" 比對結果：**true**。與 "**aple**" 比對結果：**false**。                |
| **.**       | 任意字元(換行字元除外：**\r(enter)**、**\n(換行)**、**\r\n(換行)**)。**\t** 為 tab | **/a.e/** 與 "**ape**"、"**axe**"、"**a\te**" 比對結果：**true**。與 "**a\ne**" 比對結果：**false**。 |
| **\[...]**  | 中括號裡的任意字元                                                       | **/a\[px]e/** 與 "**ape**"、"**axe**" 比對結果為 **true**。與 "**apxe**" 比對結果：**false**。       |
| **\[^...]** | 除了中括號裡的任意字元                                                     | **/a\[^px]/** 與 "**ale**" 比對結果：**true**。                                              |
| **\d**      | 數字 0 \~ 9                                                       | **/\d{3}/** 與 "**abc 123**" 比對結果：**true**。                                            |
| **\D**      | 任何非數字字元                                                         | **/\D{2,4}/** 與 "**abc 123**" 比對結果：**true**。                                          |
| **\w**      | 字母、數字、底線符號                                                      | **/\w/** 與 "**javascript**" 比對結果：**true**。與 "**%**" 比對結果：**false**。                   |
| **\W**      | 非「字母、數字、底線符號」的其它字元                                              | **/\W/** 與 "**100%**" 比對結果：**true**。                                                  |
| **\n**      | 換行字元                                                            |                                                                                       |
| **\s**      | 一個空白字元                                                          |                                                                                       |
| **\S**      | 一個非空白字元                                                         |                                                                                       |
| **\t**      | 一個 tab 字元                                                       |                                                                                       |

## 練習

修改以下原始碼，試著比對行動電話號碼：09 開頭，且總共一定要 10 個位數：

```javascript
var pattern;

var str = "";

console.log(pattern.test(str));
```

參考作法：

{% embed url="<https://codepen.io/carlos411/pen/poyJypy>" %}
