이 글은 다음 언어로만 작성되어 있습니다. 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).

과제

Which string matches the pattern ^$?

An empty string is the only match: it starts and immediately finishes.

The task once again demonstrates that anchors are not characters, but tests.

The string is empty "". The engine first matches the ^ (input start), yes it’s there, and then immediately the end $, it’s here too. So there’s a match.

튜토리얼 지도

댓글

댓글을 달기 전에 마우스를 올렸을 때 나타나는 글을 먼저 읽어주세요.
  • 추가 코멘트, 질문 및 답변을 자유롭게 남겨주세요. 개선해야 할 것이 있다면 댓글 대신 이슈를 만들어주세요.
  • 잘 이해되지 않는 부분은 구체적으로 언급해주세요.
  • 댓글에 한 줄짜리 코드를 삽입하고 싶다면 <code> 태그를, 여러 줄로 구성된 코드를 삽입하고 싶다면 <pre> 태그를 이용하세요. 10줄 이상의 코드는 plnkr, JSBin, codepen 등의 샌드박스를 사용하세요.