Skip to content

Commit f8e41e7

Browse files
committed
Complete regexp.
1 parent d2cb6cb commit f8e41e7

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

article/005-reference-date-regexp.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,42 @@ ECMAScript 中的 Date 类型是在早期 Java 中的 java.util.Date 类基础
3030

3131
### 2、RegExp类型
3232

33+
ECMAScript 通过 RegExp 类型来支持正则表达式。如下创建一个正则表达式。
34+
35+
`var expression = / pattern / flags ; `
36+
37+
一个正则包含两部分:模式(pattern)和 标志(flags)
38+
39+
正则表达式的匹配模式支持三个标志:
40+
41+
- g:全局模式(global),即模式将被应用于所有字符串,在发现第一个匹配项后继续查找。
42+
- i:不区分大小写模式(case-insensitive),在确定匹配项是忽略模式与字符串的大小写。
43+
- m:多行模式(multiline),在到达一行文本末尾时还会继续查找下一行中是否存在与模式匹配的项。
44+
45+
正则表达式就是一个模式与上述3个标志的组合体。不同组合产生不同结果,如下例子:
46+
47+
```javascript
48+
// 字面量形式定义正则表达式
49+
var pattern1 = /[bc]at/i;
50+
51+
// 构造函数定义正则
52+
var pattern2 = new RegExp("[bc]at", "i");
53+
```
54+
55+
pattern1 与 pattern2 是完全等价的两个正则表达式。
56+
57+
**⚠️ 传递给构造函数的两个参数时字符串(不能吧字面量传递给 RegExp 构造函数)。由于 RegExp 构造函数的模式参数时字符串,所以在某些情况下要对字符串进行双重转义。 _所有字符串都必须双重转义_ 那些已经转义过的字符也是如此。**
58+
59+
60+
| 字面量模式 | 等价的字符串 |
61+
| :-: | :-: |
62+
| /\[bc\]at/ |\\[bc\\]at” |
63+
| /\.at/ |\\.at” |
64+
| /name\/age/ | “name\\/age” |
65+
| /\d.\d{1,2}/ |\\d.\\d{1,2}” |
66+
67+
使用字面量和使用 RegExp 构造函数 区别:**使用字面量始终会共享同一个 RegExp 实例,而使用构造函数创建的每一个新 RegExp 实例都是一个新实例。**
68+
3369

3470

3571
### 3、Function类型

0 commit comments

Comments
 (0)