JavaScript / match()로 정규표현식에 맞는 문자열 찾기
text.match(regex)는 문자열이 정규표현식과 일치하는 부분을 찾습니다. 일치하면 배열을, 없으면 null을 반환합니다. 정규표현식의 g 플래그 유무에 따라 배열에 담기는 값과 위치·캡처 정보가 달라지므로 결과를 쓰기 전에 구분해야 합니다.
첫 일치 결과와 null 구분하기
정규표현식은 /Lo/처럼 슬래시로 감싸서 적습니다. g 없이 match()를 호출하면 처음 일치한 부분이 배열의 [0]에, 시작 위치가 index 속성에 담깁니다. 일치가 없으면 배열이 아니라 null이므로 먼저 확인하세요.
const text = 'Lorem Ipsum Dolor';
const found = text.match(/Lo/);
console.log(found[0]); // 'Lo'
console.log(found.index); // 0
const absent = text.match(/Loi/);
console.log(absent); // null
console.log(absent?.[0]); // undefined: null에서 안전하게 확인
absent[0]처럼 null을 바로 배열처럼 읽으면 오류가 납니다. 결과가 있는지만 필요하다면 정규표현식의 test()도 적합합니다. MDN의 String.match() 문서에서 반환 형태를 확인할 수 있습니다.
g·i 플래그와 캡처 그룹
i는 영어 대소문자를 무시합니다. g는 전체 일치를 찾아 일치한 문자열들을 배열로 반환하지만, 그 배열에는 개별 일치의 index와 괄호로 잡은 캡처 그룹이 들어가지 않습니다. g가 없으면 첫 일치와 함께 캡처 그룹을 [1]부터 읽을 수 있습니다.
const text = 'Lorem Ipsum Dolor';
console.log(text.match(/lo/i)[0]); // 'Lo'
console.log(text.match(/o/g)); // ['o', 'o', 'o']
const captured = text.match(/Lo(\w+)/);
console.log(captured[0]); // 'Lorem'
console.log(captured[1]); // 'rem'
console.log(captured.index); // 0
여기서 \w는 이 예제의 영문 단어 부분에 맞습니다. 한국어 단어 전체를 \w+로 찾을 수 있다고 가정하면 안 됩니다. 유니코드 문자 범위를 다루는 패턴은 별도로 설계하세요. g 검색에서도 각 일치의 위치나 캡처가 필요하면 matchAll()을 검토합니다. 정규표현식의 기초는 MDN의 정규표현식 안내에 설명되어 있습니다.
전체 예제로 결과 형태 비교하기
아래 코드를 UTF-8의 match-example.html로 저장해 브라우저에서 엽니다. 문장과 미리 정한 정규표현식을 선택해 검색합니다. 사용자가 입력한 임의의 패턴을 실행하는 도구가 아니라, g·i·캡처의 차이를 관찰하는 예제입니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>String.match 결과 비교</title>
</head>
<body>
<label for="source">검색할 문장</label>
<input id="source" type="text" value="Lorem Ipsum Dolor">
<label for="pattern">정규표현식</label>
<select id="pattern">
<option value="first">/Lo/ 첫 일치</option>
<option value="insensitive">/lo/i 대소문자 무시</option>
<option value="all">/o/g 전체 일치</option>
<option value="capture">/Lo(\w+)/ 캡처</option>
<option value="missing">/Loi/ 일치 없음</option>
</select>
<button id="search" type="button">찾기</button>
<button id="reset" type="button">처음으로</button>
<pre id="output" aria-live="polite"></pre>
<script>
const patterns = {
first: /Lo/,
insensitive: /lo/i,
all: /o/g,
capture: /Lo(\w+)/,
missing: /Loi/
};
const source = document.querySelector('#source');
const choice = document.querySelector('#pattern');
const output = document.querySelector('#output');
function show() {
const regex = patterns[choice.value];
const result = source.value.match(regex);
if (result === null) {
output.textContent = '일치 없음: null';
} else if (regex.global) {
output.textContent = `전체 일치 목록: ${JSON.stringify(result)}`;
} else {
const captured = result.length > 1 ? result.slice(1).join(', ') : '없음';
output.textContent = `첫 일치: ${result[0]}\n시작 위치: ${result.index}\n캡처: ${captured}`;
}
}
document.querySelector('#search').addEventListener('click', show);
document.querySelector('#reset').addEventListener('click', () => {
source.value = 'Lorem Ipsum Dolor';
choice.value = 'first';
show();
});
show();
</script>
</body>
</html>
처음에는 첫 일치: Lo, 시작 위치: 0이 보입니다. /o/g를 고르면 ["o","o","o"]가, /Lo(\w+)/를 고르면 전체 일치 Lorem과 캡처 rem이 표시됩니다. /Loi/는 null 안내를 보여 줍니다. 문장을 바꿔 결과가 달라지는지 확인한 뒤 ‘처음으로’를 누르면 원래 입력과 선택으로 돌아옵니다.
검색 목적에 맞는 메서드 고르기
존재 여부만 필요하면 RegExp.test(), 정규표현식 없이 고정 문자열의 위치가 필요하면 indexOf()가 간단합니다. 모든 일치의 상세 정보가 필요하면 matchAll()을 사용합니다. match()는 첫 일치의 상세 정보나 모든 일치 문자열만 필요한 경우에 적합합니다. 패턴을 바꿀 때는 결과가 null일 수 있고 g에 따라 모양이 달라진다는 점을 함께 검토하세요.




