2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
id: 587d7db7367417b2b2512b9d
|
2021-03-15 03:20:39 +00:00
|
|
|
title: 匹配字符串的开头
|
2018-10-10 22:03:03 +00:00
|
|
|
challengeType: 1
|
2020-08-04 07:14:01 +00:00
|
|
|
forumTopicId: 301349
|
2021-01-13 02:31:00 +00:00
|
|
|
dashedName: match-beginning-string-patterns
|
2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --description--
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
回顾一下之前的挑战,正则表达式可以用于查找多项匹配。 还可以查询字符串中符合指定匹配模式的字符。
|
2020-12-16 07:37:30 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
在之前的挑战中,使用字符集中前插入符号(`^`)来创建一个否定字符集,形如 `[^thingsThatWillNotBeMatched]`。 除了在字符集中使用之外,脱字符还用于匹配字符串的开始位置。
|
2020-08-04 07:14:01 +00:00
|
|
|
|
|
|
|
```js
|
|
|
|
let firstString = "Ricky is first and can be found.";
|
|
|
|
let firstRegex = /^Ricky/;
|
|
|
|
firstRegex.test(firstString);
|
|
|
|
let notFirst = "You can't find Ricky now.";
|
|
|
|
firstRegex.test(notFirst);
|
|
|
|
```
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
第一次 `test` 调用将返回 `true`,而第二次调用将返回 `false`。
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --instructions--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
在正则表达式中使用脱字符来找到 `Cal` 在字符串 `rickyAndCal` 中的开始位置。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --hints--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
你的正则表达式应该搜寻首字母大写的 `Cal`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
```js
|
|
|
|
assert(calRegex.source == '^Cal');
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
你的正则表达式不应该使用任何标志。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
assert(calRegex.flags == '');
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
你的正则表达式应该匹配字符串 `Cal` 的开始位置。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
```js
|
|
|
|
assert(calRegex.test('Cal and Ricky both like racing.'));
|
|
|
|
```
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
你的正则表达式不应该匹配中间包含 `Cal` 的字符串。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
assert(!calRegex.test('Ricky and Cal both like racing.'));
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
2020-08-04 07:14:01 +00:00
|
|
|
|
2021-01-13 02:31:00 +00: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 07:37:30 +00:00
|
|
|
# --solutions--
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
```js
|
|
|
|
let rickyAndCal = "Cal and Ricky both like racing.";
|
|
|
|
let calRegex = /^Cal/; // Change this line
|
|
|
|
let result = calRegex.test(rickyAndCal);
|
|
|
|
```
|