정규표현식은 크게 다음과 같은 역할을 수행한다.
- 문자 검색
- 문자 대체
- 문자 추출
테스트 사이트
RegExr: Learn, Build, & Test RegEx
정규식 생성 방법
new RegExp('표현','옵션')
new RegExp('[a-z]','gi')
/표현/옵션
/[a-z]/gi
예제 문자
const str = `
010-1234-5678
themail1@mail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The fox and the dog
abbcccdddd
`;
const regexp = new RegExp('the', 'gi');
const regexp2 = /the/gi;
console.log(str.match(regexp));
console.log(str.match(regexp2));
메소드
| 메소드 | 문법 | 설명 |
|---|
| test | 정규식.test(문자열) | 일치여부 반환(불린값) |
| match | 문자열.match(정규식) | 일치하는 문자의 배열 반환 |
| replace | 문자열.replace(정규식, 대체문자) | 일치하는 문자를 대체 |
const regexp = /fox/gi;
console.log(regexp.test(str));
console.log(str.replace(regexp, 'AAA'));
플래그
| 플래그 | 설명 |
|---|
| g | 모든 문자 일치 (global) |
| i | 영어 대소문자를 구분하지 않고 일치 (ignore case) |
| m | 여러 줄 일치 (multi line) |
패턴 1
| 패턴 | 설명 |
|---|
| ^ab | 줄의 시작에 있는 ab와 일치 |
| ab$ | 줄의 끝에 있는 ab와 일치 |
| . | 임의의 한 문자와 일치 |
| a | b |
| ab? | b가 없거나 b와 일치 |
| {3} | 3개 연속 일치 |
| {3,} | 3개 이상 연속 일치 |
| {3,5} | 3개 이상 5개 이하 연속 일치 |
const str = `
010-1234-5678
themail1@mail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The fox and the dog
abbcccdddd
d
`;
console.log(str.match(/d$/gm));
console.log(str.match(/^t/gim));
console.log(str.match(/h..p/gim));
console.log(str.match(/d{2,}/gim));
패턴 2
| 패턴 | 설명 |
|---|
| [abc] | a 또는 b 또는 c |
| [a-z] | a에서 z 사이의 문자 구간에 일치 |
| [A-Z] | A에서 Z 사이의 문자 구간에 일치 |
| [0-9] | 0부터 9 사이의 문자 구간에 일치 |
| [가-힇] | 가부터 힇 사이의 문자 구간에 일치 |
| \w | 63개 문자(word, 대소영문 52 + 숫자 10 + _)에 일치 |
| \b | 63개 문자에 일치하지 않는 문자 경계 (boundary) |
| \d | 숫자(digit)에 일치 |
| \s | 공백(space, tab 등)에 일치 |
| (?=) | 앞쪽 일치 |
| (?<=) | 뒤쪽 일치 |
const str = `
010-1234-5678
themail1@mail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The fox and the dog
abbcccdddd
d
`;
console.log(str.match(/[0-9]{3,}/g));
console.log(str.match(/\w{8,}/g));
console.log(str.match(/\bf\w{1,}\b/g));
console.log(str.match(/\d/g));
console.log(str.match(/\s/g));
const spaceStr = ` he llo world
`;
console.log(spaceStr.replace(/\s/g, ''));
console.log(str.match(/.{1,}(?=@)/g));
console.log(str.match(/(?<=@).{1,}/g));