Skip to content

Commit d2215d7

Browse files
committed
2019.03.15
1 parent 2ddeeca commit d2215d7

2 files changed

Lines changed: 99 additions & 2 deletions

File tree

Cute-JavaScript/Cute-Regular/1.字符匹配.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,4 @@ s.match(r3)[0]; // id="leo"
172172
**tips2**:使用惰性匹配,但效率低,有**回溯**问题。
173173
**tips3**:最终优化。
174174

175-
### 6. 小结
176-
掌握好字符组和量词就可以解决大部分情况,也算是入门了。
177175

Cute-JavaScript/Cute-Regular/3.括号的使用.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,102 @@ RegExp.$3; // "14"
4444
```
4545

4646
### 2. 反向引用
47+
48+
使用 `\n` 表示第 `n` 个分组,比如 `\1` 表示第 `1` 个分组:
49+
50+
```js
51+
let r = /\d{4}(-|\/|\.)\d{2}\1\d{2}/;
52+
r.test("2019-03-15");
53+
r.test("2019/03/15");
54+
r.test("2019.03.15");
55+
r.test("2019-03/15");
56+
```
57+
58+
* 多个括号嵌套
59+
60+
按照开括号的顺序:
61+
62+
```js
63+
let r = /^((\d)(\d(\d)))\1\2\3\4$/;
64+
let s = "1231231233";
65+
r.test(s);
66+
console.log([RegExp.$1,RegExp.$2,RegExp.$3,RegExp.$4]);
67+
// ["123", "1", "23", "3"]
68+
```
69+
70+
* 特殊情况
71+
72+
`\10` 表示的是第 10 个分组,若要匹配 `\``0` 时,使用 `(?:\1)0``\1(?:0)`
73+
74+
```js
75+
let r = /(1)(2)(3)(4)(5)(6)(7)(8)(9)(#) \10+/;
76+
let s = "123456789# #####";
77+
r.test(s); // true
78+
```
79+
80+
* 当引用不存在的分组
81+
82+
如匹配 `\2` 是前面不存在,则匹配 `\2` 本身,即对 `2` 的转义:
83+
```js
84+
let r = /\1\2\3\4/;
85+
r.test("\1\2\3\4"); // true
86+
"\1\2\3\4".split('');// ["", "", "", ""]
87+
```
88+
89+
* 分组后面有量词
90+
91+
当分组后面有量词的话,则捕获的是最后一次的匹配:
92+
```js
93+
"12345".match(/(\d)+/); // ["12345", "5", index: 0, input: "12345"]
94+
95+
/(\d)+ \1/.test("12345 1"); // false
96+
/(\d)+ \1/.test("12345 5"); // true
97+
```
98+
99+
### 3. 相关案例
100+
101+
这里只写出核心代码。
102+
103+
* 模拟字符串 `trim` 方法
104+
105+
```js
106+
// 1 匹配首尾空白符,替换成空字符
107+
" aaa ".replace(/^\s+|\s+$/g, ""); // "aaa"
108+
109+
// 2 匹配整个字符串,再用引用提取对应数据
110+
" aaa ".replace(/^\s*(.*?)\s*$/g, "$1");// "aaa"
111+
```
112+
113+
* 每个单词首字母大写
114+
115+
```js
116+
"hi leo hi boy!".toLowerCase().replace(
117+
/(?:^|\s)\w/g,
118+
c => c.toUpperCase()
119+
);
120+
// "Hi Leo Hi Boy!"
121+
```
122+
123+
* 驼峰化 和 中划线化
124+
125+
```js
126+
"-leo-and-pingan".replace(/[-_\s]+(.)?/g,
127+
(match, c) => c ? c.toUpperCase() : ''
128+
);
129+
// "LeoAndPingan"
130+
131+
"LeoAndPingan".replace(/([A-Z])/g, "-$1").replace(
132+
/[-_\s]+g/,"-"
133+
).toLowerCase();
134+
// "-leo-and-pingan"
135+
```
136+
137+
* 匹配成对HTML标签
138+
139+
匹配成对标签 `<h1>leo<\h1>`,而不匹配不成对标签 `<h1>leo<\h2>`
140+
```js
141+
let r = /<([^>]+)>[\d\D]*<\/\1>/;
142+
r.test("<h1>leo leo leo</h1>"); // true
143+
r.test("<a>leo leo leo</a>"); // true
144+
r.test("<h1>leo leo leo</h2>"); // false
145+
```

0 commit comments

Comments
 (0)