17일 10월 2019
이 글은 다음 언어로만 작성되어 있습니다. English, 日本語, Русский, 简体中文. 한국어 번역에 참여해주세요.

Multiline mode of anchors ^ $, flag "m"

The multiline mode is enabled by the flag m.

It only affects the behavior of ^ and $.

In the multiline mode they match not only at the beginning and the end of the string, but also at start/end of line.

Searching at line start ^

In the example below the text has multiple lines. The pattern /^\d/gm takes a digit from the beginning of each line:

let str = `1st place: Winnie
2nd place: Piglet
3rd place: Eeyore`;

alert( str.match(/^\d/gm) ); // 1, 2, 3

Without the flag m only the first digit is matched:

let str = `1st place: Winnie
2nd place: Piglet
3rd place: Eeyore`;

alert( str.match(/^\d/g) ); // 1

That’s because by default a caret ^ only matches at the beginning of the text, and in the multiline mode – at the start of any line.

주의:

“Start of a line” formally means “immediately after a line break”: the test ^ in multiline mode matches at all positions preceeded by a newline character \n.

And at the text start.

Searching at line end $

The dollar sign $ behaves similarly.

The regular expression \d$ finds the last digit in every line

let str = `Winnie: 1
Piglet: 2
Eeyore: 3`;

alert( str.match(/\d$/gm) ); // 1,2,3

Without the flag m, the dollar $ would only match the end of the whole text, so only the very last digit would be found.

주의:

“End of a line” formally means “immediately before a line break”: the test $ in multiline mode matches at all positions succeeded by a newline character \n.

And at the text end.

Searching for \n instead of ^ $

To find a newline, we can use not only anchors ^ and $, but also the newline character \n.

What’s the difference? Let’s see an example.

Here we search for \d\n instead of \d$:

let str = `Winnie: 1
Piglet: 2
Eeyore: 3`;

alert( str.match(/\d\n/gm) ); // 1\n,2\n

As we can see, there are 2 matches instead of 3.

That’s because there’s no newline after 3 (there’s text end though, so it matches $).

Another difference: now every match includes a newline character \n. Unlike the anchors ^ $, that only test the condition (start/end of a line), \n is a character, so it becomes a part of the result.

So, a \n in the pattern is used when we need newline characters in the result, while anchors are used to find something at the beginning/end of a line.

튜토리얼 지도

댓글

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