정의 및 사용 방법
문자열에서 match() 함수는
주어진 정규 표현식 패턴을 사용하여 문자열 내에서 매치(match, 일치)되는 첫 번째 부분을 찾아내는 함수입니다.
특징
- 이 함수는 대소문자를 구분합니다.
- 일치하는 부분이 발견되면 해당 부분을 포함하는 배열을 반환하며,
- 일치하는 부분이 없으면
null을 반환합니다. - 이메일 주소, 전화번호, URL과 같은 특정 패턴의 문자열을 검사할 때 유용합니다.
기본 예제
const str = "apple orange banana apple";
/* 문자열에서
첫 번째로 일치하는 패턴만 찾아서 배열로 반환합니다. */
const pattern = /apple/;
const result = str.match(pattern);
console.log(result); // 출력: ["apple"]
console.log(result.length); // 출력: 1
console.log(result[0]); // 출력: "apple"
/* 만약 전체 텍스트에서 모든 일치하는 패턴을 찾고 싶다면
정규 표현식에 g (글로벌 검색) 플래그를 추가합니다. */
const globalPattern = /apple/g;
const globalResult = str.match(globalPattern);
console.log(globalResult); // 출력: ["apple", "apple"]
console.log(globalResult.length); // 출력: 2
console.log(globalResult[0]); // 출력: "apple"
console.log(globalResult[1]); // 출력: "apple"
/* 특정 패턴의 문자열을 검사하기
이메일 주소 패턴을 검색 */
const userInfo = "내 이메일 주소는 user@example.com 입니다.";
const searchEmailPattern = /\w+@\w+\.\w+/g;
const searchEmailResult = userInfo.match(searchEmailPattern);
console.log(searchEmailResult); // 출력: ["user@example.com"]
console.log(searchEmailResult.length); // 출력: 1
console.log(searchEmailResult[0]); // 출력: "user@example.com"
match() 함수의 형식은 다음과 같습니다.
구문
str.match(regexp);
str은 검색 대상이 되는 문자열입니다.
매개변수
regexp |
|
|---|
반환 값
일치하는 부분이 발견되면 해당 부분을 포함하는 배열을 반환하며, 일치하는 부분이 없으면 null을 반환합니다.
매개변수와 반환 값
매개변수가 없을 경우
match() 함수의 매개변수가 없을 경우, 다시 말해 아무런 인자를 전달하지 않을 경우 배열에 빈 문자열("")을 반환합니다.
const str = "Hello, World!";
const result = str.match();
console.log(result); // 출력: [""]
console.log(result.length); // 출력: 1
코드 부연설명
배열에서 length 속성은 배열에 포함된 요소의 개수를 숫자로 반환합니다.
매개변수가 빈 문자열("")일 경우
매개변수가 빈 문자열("")일 경우 배열에 빈 문자열("")을 반환합니다.
const str = "Hello, World!";
const result = str.match("");
console.log(result); // 출력: [""]
console.log(result.length); // 출력: 1
매개변수가 공백 문자열(" ")일 경우
매개변수가 공백 문자열(" ")일 경우 해당 문자열을 패턴으로 인식하여 문자열 내에서 해당 공백 문자열과 일치하는 부분을 찾습니다. 반환 값은 일치하는 공백 문자열을 담은 배열이 됩니다.
const str = "Hello, World!";
const result = str.match(" ");
console.log(result); // 출력: [" "]
console.log(result.length); // 출력: 1
매개변수와 일치하는 부분이 여러 개인 경우
매개변수와 일치하는 부분이 여러 개인 경우 문자열에서 첫 번째로 일치하는 패턴만 찾아서 배열로 반환합니다.
const str = "apple orange banana apple";
const pattern = /apple/;
const result = str.match(pattern);
console.log(result); // 출력: ["apple"]
console.log(result.length); // 출력: 1
일치하는 부분이 여러 개일 때 모두 반환하고 싶은 경우
만약 전체 텍스트에서 모든 일치하는 패턴을 찾고 싶다면 정규 표현식에 g (글로벌 검색) 플래그를 추가합니다.
const str = "apple orange banana apple";
const pattern = /apple/g; // <= g (글로벌 검색) 플래그 추가
const result = str.match(pattern);
console.log(result); // 출력: ["apple", "apple"]
console.log(result[0]);
console.log(result[1]);
console.log(result.length); // 출력: 2
정규 표현식의 플래그는 /regex/flags와 같이 작성합니다. regex 자리에 정규표현식 패턴이 오고, flags에 플래그가 옵니다. 위 코드 예제에서는 /apple/g로 작성한 것이고 정규식 /apple/에 g (글로벌 검색) 플래그를 추가한 것입니다.
정규 표현식의 플래그는 다음과 같습니다.
| 플래그 | 설명 |
|---|---|
i |
Case-insensitive 플래그.
대소문자를 구분하지 않고 패턴을 검색합니다. |
g |
Global 플래그.
대상이 되는 문자열 내에서 패턴과 일치하는 모든 문자열을 글로벌로 검색합니다. |
m |
Multiline 플래그.
다중 행 문자열에서의 검색을 활성화합니다. |
매개 변수와 일치하는 부분이 없는 경우
일치하는 패턴이 없으면 null이 반환됩니다.
const str = "Hi, World!";
const pattern = /Hello/;
const result = str.match(pattern);
console.log(result); // 출력: null
이 함수의 관련 함수를 참조하세요.
활용 예제
match() 함수는 이메일 주소, 전화번호, URL과 같은 특정 패턴의 문자열을 검사할 때 유용합니다. 또한, 다양한 상황에서 유용하게 활용될 수 있습니다. 여기에는 몇 가지 예제를 다룹니다.
이메일 주소 검사
const text = "문의는 help@example.com 또는 support@example.org 으로 연락 주시기 바랍니다.";
const emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g;
const emailMatches = text.match(emailPattern);
console.log(emailMatches);
// 출력: ["help@example.com", "support@example.org"]
핸드폰번호 검사
const text = "문의는 010-9876-5432 또는 010-9876-5439로 연락 주세요.";
const phonePattern = /\d{3}-\d{4}-\d{4}/g;
const phoneMatches = text.match(phonePattern);
console.log(phoneMatches);
// 출력: ["010-9876-5432", "010-9876-5439"]
URL 검사
const text = "더 많은 정보는 https://www.example.co.kr에서 확인하세요.";
const urlPattern = /\b(?:https?:\/\/)?(?:www\.)?[a-zA-Z0-9-]+(?:\.[a-z]{2,})+(?:\/[^\s]*)?\b/g;
const urlMatches = text.match(urlPattern);
console.log(urlMatches);
// 출력: ["https://www.example.co.kr"]
HTML에서 태그를 추출
const html = '<div class="container"><p>Hello, <b>world!</b></p></div>';
const tagPattern = /<[^>]+>/g;
const tags = html.match(tagPattern);
console.log(tags);
// 출력: ["<div class="container">", "<p>", "<b>", "</b></p>", "</div>"]
CSS 클래스 추출
const css = '.header { color: #333; } .main-content { font-size: 16px; }';
const classPattern = /\.([a-zA-Z-_\d]+)/g;
const classes = css.match(classPattern);
console.log(classes);
// 출력: [".header", ".main-content"]
호환성
| 메서드 |
데스크탑 Chrome
|
데스크탑데스크탑 Edge
|
데스크탑 Firefox
|
Safari
|
Node.js
|
|---|---|---|---|---|---|
match()
|
1 | 12 | 1 | 1 | 0.10 |
명세서
| 명세서 사양 | |
|---|---|
match()
|
ECMAScript Language Specification #sec-string.prototype.match |