6日 十二月 2019
本资料仅提供以下语言版本:English, 日本語, Русский。请 帮助我们 将其翻译为 简体中文 版本。

Anchors: string start ^ and end $

The caret ^ and dollar $ characters have special meaning in a regexp. They are called “anchors”.

The caret ^ matches at the beginning of the text, and the dollar $ – at the end.

For instance, let’s test if the text starts with Mary:

let str1 = "Mary had a little lamb";
alert( /^Mary/.test(str1) ); // true

The pattern ^Mary means: “string start and then Mary”.

Similar to this, we can test if the string ends with snow using snow$:

let str1 = "it's fleece was white as snow";
alert( /snow$/.test(str1) ); // true

In these particular cases we could use string methods startsWith/endsWith instead. Regular expressions should be used for more complex tests.

Testing for a full match

Both anchors together ^...$ are often used to test whether or not a string fully matches the pattern. For instance, to check if the user input is in the right format.

Let’s check whether or not a string is a time in 12:34 format. That is: two digits, then a colon, and then another two digits.

In regular expressions language that’s \d\d:\d\d:

let goodInput = "12:34";
let badInput = "12:345";

let regexp = /^\d\d:\d\d$/;
alert( regexp.test(goodInput) ); // true
alert( regexp.test(badInput) ); // false

Here the match for \d\d:\d\d must start exactly after the beginning of the text ^, and the end $ must immediately follow.

The whole string must be exactly in this format. If there’s any deviation or an extra character, the result is false.

Anchors behave differently if flag m is present. We’ll see that in the next article.

Anchors have “zero width”

Anchors ^ and $ are tests. They have zero width.

In other words, they do not match a character, but rather force the regexp engine to check the condition (text start/end).

任务

什么字符串可以匹配模式 ^$

唯一一个匹配的字符串是空字符串:它的开始紧跟着结束。

这个题目再一次说明了锚不是一个字符串,而是一个测试。

对于空字符串 "",正则表达式引擎将会首先匹配模式 ^(输入开始),匹配成功之后,会紧跟着检查模式 $,也匹配成功。所以空字符串是匹配 ^$ 的。

教程路线图

评论

在评论之前先阅读本内容…
  • 如果你发现教程有错误,或者有其他需要修改和提升的地方 — 请 提交一个 GitHub issue 或 pull request,而不是在这评论。
  • 如果你对教程的内容有不理解的地方 — 请详细说明。
  • 使用 <code> 标签插入只有几个词的代码,插入多行代码可以使用 <pre> 标签,对于超过 10 行的代码,建议你使用沙箱(plnkrJSBincodepen…)