2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: 587d7db4367417b2b2512b93
|
2020-12-16 00:37:30 -07:00
|
|
|
title: 全局匹配
|
2018-10-10 18:03:03 -04:00
|
|
|
challengeType: 1
|
2020-08-04 15:14:01 +08:00
|
|
|
forumTopicId: 301342
|
2021-01-13 03:31:00 +01:00
|
|
|
dashedName: find-more-than-the-first-match
|
2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --description--
|
|
|
|
|
2020-08-04 15:14:01 +08:00
|
|
|
到目前为止,只能提取或搜寻一次模式匹配。
|
|
|
|
|
|
|
|
```js
|
|
|
|
let testStr = "Repeat, Repeat, Repeat";
|
|
|
|
let ourRegex = /Repeat/;
|
|
|
|
testStr.match(ourRegex);
|
|
|
|
// Returns ["Repeat"]
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
若要多次搜寻或提取模式匹配,可以使用`g`标志。
|
2020-08-04 15:14:01 +08:00
|
|
|
|
|
|
|
```js
|
|
|
|
let repeatRegex = /Repeat/g;
|
|
|
|
testStr.match(repeatRegex);
|
|
|
|
// Returns ["Repeat", "Repeat", "Repeat"]
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --instructions--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
使用正则表达式`starRegex`,从字符串`twinkleStar`中匹配到所有的`"Twinkle"`单词并提取出来。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
**注意:**
|
|
|
|
在正则表达式上可以有多个标志,比如`/search/gi`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --hints--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
你的正则表达式`starRegex`应该使用全局标志`g`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(starRegex.flags.match(/g/).length == 1);
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
你的正则表达式`starRegex`应该使用忽略大小写标志`i`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(starRegex.flags.match(/i/).length == 1);
|
|
|
|
```
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
你的匹配应该匹配单词`'Twinkle'`的两个匹配项。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(
|
|
|
|
result.sort().join() ==
|
|
|
|
twinkleStar
|
|
|
|
.match(/twinkle/gi)
|
|
|
|
.sort()
|
|
|
|
.join()
|
|
|
|
);
|
|
|
|
```
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
你的匹配`结果`应该包含两个元素。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(result.length == 2);
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
2020-08-04 15:14:01 +08:00
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```js
|
|
|
|
let twinkleStar = "Twinkle, twinkle, little star";
|
|
|
|
let starRegex = /change/; // Change this line
|
|
|
|
let result = twinkleStar; // Change this line
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --solutions--
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
```js
|
|
|
|
let twinkleStar = "Twinkle, twinkle, little star";
|
|
|
|
let starRegex = /twinkle/gi;
|
|
|
|
let result = twinkleStar.match(starRegex);
|
|
|
|
```
|