2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: 587d7db7367417b2b2512b9d
|
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: 301349
|
2021-01-13 03:31:00 +01:00
|
|
|
dashedName: match-beginning-string-patterns
|
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
|
|
|
回顾一下之前的挑战,正则表达式可以用于查找多项匹配。还可以查询字符串中符合指定匹配模式的字符。
|
2020-12-16 00:37:30 -07:00
|
|
|
|
|
|
|
在之前的挑战中,使用`字符集`中的`插入`符号(`^`)来创建一个`否定字符集`,形如`[^thingsThatWillNotBeMatched]`。在`字符集`之外,`插入`符号用于字符串的开头搜寻匹配模式。
|
2020-08-04 15:14:01 +08:00
|
|
|
|
|
|
|
```js
|
|
|
|
let firstString = "Ricky is first and can be found.";
|
|
|
|
let firstRegex = /^Ricky/;
|
|
|
|
firstRegex.test(firstString);
|
|
|
|
// Returns true
|
|
|
|
let notFirst = "You can't find Ricky now.";
|
|
|
|
firstRegex.test(notFirst);
|
|
|
|
// Returns false
|
|
|
|
```
|
|
|
|
|
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
|
|
|
在正则表达式中使用`^`符号,以匹配仅在字符串`rickyAndCal`的开头出现的`"Cal"`。
|
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
|
|
|
你的正则表达式应该搜寻有一个大写字母的`'Cal'`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(calRegex.source == '^Cal');
|
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(calRegex.flags == '');
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
你的正则表达式应该匹配字符串开头的`'Cal'`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(calRegex.test('Cal and Ricky both like racing.'));
|
|
|
|
```
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
你的正则表达式不应该匹配字符串中间的`'Cal'`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(!calRegex.test('Ricky and Cal both like racing.'));
|
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 rickyAndCal = "Cal and Ricky both like racing.";
|
|
|
|
let calRegex = /change/; // Change this line
|
|
|
|
let result = calRegex.test(rickyAndCal);
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --solutions--
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
```js
|
|
|
|
let rickyAndCal = "Cal and Ricky both like racing.";
|
|
|
|
let calRegex = /^Cal/; // Change this line
|
|
|
|
let result = calRegex.test(rickyAndCal);
|
|
|
|
```
|