2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: 587d7db4367417b2b2512b92
|
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: 301340
|
2021-01-13 03:31:00 +01:00
|
|
|
dashedName: extract-matches
|
2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --description--
|
|
|
|
|
|
|
|
到目前为止,只是检查了一个匹配模式是否存在于字符串中。还可以使用`.match()`方法来提取找到的实际匹配项。
|
|
|
|
|
|
|
|
可以使用字符串来调用`.match()`方法,并在括号内传入正则表达式。以下是一个示例:
|
2020-08-04 15:14:01 +08:00
|
|
|
|
|
|
|
```js
|
|
|
|
"Hello, World!".match(/Hello/);
|
|
|
|
// Returns ["Hello"]
|
|
|
|
let ourStr = "Regular expressions";
|
|
|
|
let ourRegex = /expressions/;
|
|
|
|
ourStr.match(ourRegex);
|
|
|
|
// Returns ["expressions"]
|
|
|
|
```
|
|
|
|
|
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
|
|
|
利用`.match()`方法提取单词`coding`。
|
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
|
|
|
`结果`应该包含单词`coding`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(result.join() === 'coding');
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
你的正则表达式`codingRegex`应该搜寻`coding`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(codingRegex.source === 'coding');
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
你应该使用`.match()`方法。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(code.match(/\.match\(.*\)/));
|
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 extractStr = "Extract the word 'coding' from this string.";
|
|
|
|
let codingRegex = /change/; // Change this line
|
|
|
|
let result = extractStr; // Change this line
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --solutions--
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
```js
|
|
|
|
let extractStr = "Extract the word 'coding' from this string.";
|
|
|
|
let codingRegex = /coding/; // Change this line
|
|
|
|
let result = extractStr.match(codingRegex); // Change this line
|
|
|
|
```
|