2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: 587d7db4367417b2b2512b93
|
|
|
|
challengeType: 1
|
2020-08-04 15:14:01 +08:00
|
|
|
forumTopicId: 301342
|
2020-10-01 17:54:21 +02:00
|
|
|
title: 全局匹配
|
2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
|
|
|
|
## Description
|
2020-08-04 15:14:01 +08:00
|
|
|
<section id='description'>
|
|
|
|
到目前为止,只能提取或搜寻一次模式匹配。
|
|
|
|
|
|
|
|
```js
|
|
|
|
let testStr = "Repeat, Repeat, Repeat";
|
|
|
|
let ourRegex = /Repeat/;
|
|
|
|
testStr.match(ourRegex);
|
|
|
|
// Returns ["Repeat"]
|
|
|
|
```
|
|
|
|
|
|
|
|
若要多次搜寻或提取模式匹配,可以使用<code>g</code>标志。
|
|
|
|
|
|
|
|
```js
|
|
|
|
let repeatRegex = /Repeat/g;
|
|
|
|
testStr.match(repeatRegex);
|
|
|
|
// Returns ["Repeat", "Repeat", "Repeat"]
|
|
|
|
```
|
|
|
|
|
|
|
|
</section>
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
## Instructions
|
2020-08-04 15:14:01 +08:00
|
|
|
<section id='instructions'>
|
|
|
|
使用正则表达式<code>starRegex</code>,从字符串<code>twinkleStar</code>中匹配到所有的<code>"Twinkle"</code>单词并提取出来。
|
|
|
|
<strong>注意:</strong><br>在正则表达式上可以有多个标志,比如<code>/search/gi</code>。
|
|
|
|
</section>
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
## Tests
|
|
|
|
<section id='tests'>
|
|
|
|
|
|
|
|
```yml
|
|
|
|
tests:
|
2020-08-04 15:14:01 +08:00
|
|
|
- text: 你的正则表达式<code>starRegex</code>应该使用全局标志<code>g</code>。
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert(starRegex.flags.match(/g/).length == 1);
|
2020-08-04 15:14:01 +08:00
|
|
|
- text: 你的正则表达式<code>starRegex</code>应该使用忽略大小写标志<code>i</code>。
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert(starRegex.flags.match(/i/).length == 1);
|
2020-08-04 15:14:01 +08:00
|
|
|
- text: "你的匹配应该匹配单词<code>'Twinkle'</code>的两个匹配项。"
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert(result.sort().join() == twinkleStar.match(/twinkle/gi).sort().join());
|
2020-08-04 15:14:01 +08:00
|
|
|
- text: 你的匹配<code>结果</code>应该包含两个元素。
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert(result.length == 2);
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Challenge Seed
|
|
|
|
<section id='challengeSeed'>
|
|
|
|
|
|
|
|
<div id='js-seed'>
|
|
|
|
|
|
|
|
```js
|
|
|
|
let twinkleStar = "Twinkle, twinkle, little star";
|
|
|
|
let starRegex = /change/; // Change this line
|
|
|
|
let result = twinkleStar; // Change this line
|
|
|
|
```
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Solution
|
|
|
|
<section id='solution'>
|
|
|
|
|
|
|
|
```js
|
2020-08-04 15:14:01 +08:00
|
|
|
let twinkleStar = "Twinkle, twinkle, little star";
|
|
|
|
let starRegex = /twinkle/gi;
|
|
|
|
let result = twinkleStar.match(starRegex);
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
2020-08-04 15:14:01 +08:00
|
|
|
|
2018-10-10 18:03:03 -04:00
|
|
|
</section>
|