라이브러리
[JAVASCRIPT] str.match(regex) - 정규식과 매칭되는 결과 반환
JavaScript에서 str.match(regex)란?
JavaScript의 `str.match(regex)` 메서드는 문자열 `str`에 정규표현식 `regex`을 적용하여 일치하는 패턴을 찾습니다. 이 메서드는 일치하는 패턴을 배열로 반환합니다. 만약 일치하는 패턴이 없다면 `null`을 반환합니다.
정규표현식(regex) 예제
정규표현식은 특정 패턴을 표현하기 위해 사용하는 문자열입니다. 정규표현식은 다음과 같은 형태로 구성됩니다.
- 특수문자 (예: `.`, `^`, `$`, `*`, `+`, `?`, `{`, `}`, `[`, `]`, `(`, `)`, `|`, ``)
- 일반문자 (예: `a`, `b`, `c`, ..., `z`, `A`, `B`, `C`, ..., `Z`, `0`, `1`, `2`, ..., `9`)
str.match(regex) 예제
# 1. 문자열의 시작과 끝
#hostingforum.kr
javascript
const str = "Hello, World!";
const regex = /^Hello/;
const match = str.match(regex);
console.log(match); // ["Hello"]
# 2. 특정 문자열 찾기
#hostingforum.kr
javascript
const str = "Hello, World!";
const regex = /World/;
const match = str.match(regex);
console.log(match); // ["World"]
# 3. 특정 문자열 찾기 (대소문자 구분)
#hostingforum.kr
javascript
const str = "Hello, World!";
const regex = /world/i;
const match = str.match(regex);
console.log(match); // ["world"]
# 4. 특정 문자열 찾기 (정규표현식)
#hostingforum.kr
javascript
const str = "Hello, World!";
const regex = /w+/;
const match = str.match(regex);
console.log(match); // ["Hello", "World"]
# 5. 특정 문자열 찾기 (정규표현식 - 반복)
#hostingforum.kr
javascript
const str = "Hello, Hello, World!";
const regex = /Hello/g;
const match = str.match(regex);
console.log(match); // ["Hello", "Hello"]
# 6. 특정 문자열 찾기 (정규표현식 - 그룹)
#hostingforum.kr
javascript
const str = "Hello, World!";
const regex = /Hello, (w+)/;
const match = str.match(regex);
console.log(match); // ["Hello, World", "World"]
str.match(regex) 메서드의 반환값
`str.match(regex)` 메서드는 일치하는 패턴을 배열로 반환합니다. 만약 일치하는 패턴이 없다면 `null`을 반환합니다.
str.match(regex) 메서드의 옵션
`str.match(regex)` 메서드는 다음과 같은 옵션을 지원합니다.
- `g` (global) 옵션: 전역 검색을 수행합니다.
- `i` (ignoreCase) 옵션: 대소문자를 무시합니다.
- `m` (multiline) 옵션: 여러 줄을 검색합니다.
- `y` (sticky) 옵션: 일치하는 위치에서 검색합니다.
str.match(regex) 메서드의 예외
`str.match(regex)` 메서드는 다음과 같은 예외를 발생시킬 수 있습니다.
- `TypeError`: `str`이 문자열이 아닌 경우.
- `SyntaxError`: `regex`이 정규표현식이 아닌 경우.
str.match(regex) 메서드의 참고문서
- MDN Web Docs: `String.prototype.match()`
- Mozilla Developer Network: `String.prototype.match()`
str.match(regex) 메서드의 예제
#hostingforum.kr
javascript
const str = "Hello, World!";
const regex = /Hello/g;
const match = str.match(regex);
console.log(match); // ["Hello", "Hello"]
const regex2 = /world/i;
const match2 = str.match(regex2);
console.log(match2); // ["world"]
str.match(regex) 메서드의 참고사항
- `str.match(regex)` 메서드는 일치하는 패턴을 배열로 반환합니다.
- `str.match(regex)` 메서드는 전역 검색을 수행할 수 있습니다.
- `str.match(regex)` 메서드는 대소문자를 무시할 수 있습니다.
- `str.match(regex)` 메서드는 여러 줄을 검색할 수 있습니다.
- `str.match(regex)` 메서드는 일치하는 위치에서 검색할 수 있습니다.
- `str.match(regex)` 메서드는 `TypeError`와 `SyntaxError` 예외를 발생시킬 수 있습니다.
댓글목록
등록된 댓글이 없습니다.