정규표현식

김주언·2022년 8월 10일

자바스크립트

목록 보기
6/8

정규표현식은 크게 다음과 같은 역할을 수행한다.

  1. 문자 검색
  2. 문자 대체
  3. 문자 추출

테스트 사이트

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'));  // str을 const가 아닌 let으로 선언하면 변경 가능

플래그

플래그설명
g모든 문자 일치 (global)
i영어 대소문자를 구분하지 않고 일치 (ignore case)
m여러 줄 일치 (multi line)

패턴 1

패턴설명
^ab줄의 시작에 있는 ab와 일치
ab$줄의 끝에 있는 ab와 일치
.임의의 한 문자와 일치
ab
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));     // multi line, ['d', 'd']
console.log(str.match(/^t/gim));    // ['t', 'T']
console.log(str.match(/h..p/gim));  // ['http']
console.log(str.match(/d{2,}/gim)); // ['dddd']

패턴 2

패턴설명
[abc]a 또는 b 또는 c
[a-z]a에서 z 사이의 문자 구간에 일치
[A-Z]A에서 Z 사이의 문자 구간에 일치
[0-9]0부터 9 사이의 문자 구간에 일치
[가-힇]가부터 힇 사이의 문자 구간에 일치
\w63개 문자(word, 대소영문 52 + 숫자 10 + _)에 일치
\b63개 문자에 일치하지 않는 문자 경계 (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));    // ['010', '1234', '5678', '7035']
console.log(str.match(/\w{8,}/g));     // ['themail1', '7035c60c', 'abbcccdddd']
console.log(str.match(/\bf\w{1,}\b/g)); // 소문자 f로 시작하는 모든 단어 찾기
console.log(str.match(/\d/g));          // 숫자 찾기
console.log(str.match(/\s/g));          // 공백 찾기 (줄바꿈\n 포함)

const spaceStr = `    he llo world

`;

console.log(spaceStr.replace(/\s/g, '')); // 공백 찾기 활용 -> 찾아서 공백 없애기, hello world 출력됨

console.log(str.match(/.{1,}(?=@)/g));    // @ 기호 앞 문자 찾기, themail
console.log(str.match(/(?<=@).{1,}/g));   // @ 기호 뒤 문자 찾기, mail.com
profile
학생 점심을 좀 차리시길 바랍니다

0개의 댓글