본문 바로가기

프론트엔드 공부/javscript

정규식표현 패턴(표현)

#패턴(표현) 정리

 

| 패턴       | 설명                           |

| ^ab        | 줄(line) 시작에 있는 ab와 일치 |

| ab$        | 줄(line)끝에 있는 ab와 일치    |

| .          | 임의의 한 문자와 일치          |

| a|b  | a또는b와 일치                  |

| ab?        | b가 없거나 b와 일치            |

 

{3} | 3개연속일치

{3,} | 3개 이상 연속 일치

{3,5} | 3개이상 5개 이하(3-5개)연속일치

 

[abc] | a또는 b또는 c

[a-z] | a부터 z사이의 문자 구간에 일치(영어소문자)

[A-Z] A부터 Z사이의 문자구간에 일치(영어대문자)

[0-9] | 0부터 9 사이 문자구간에 일치(숫자)

[가-힣] 가부터 힣 사이의 문자구간에 일치(한글)

 

\w | 63개 문자(word,대소영문,숫자,_)에 일치

\b | 63개 문자에 일치하지 않는 문자 경계(boundary)

: .,@공백등 제외

\d | 숫자(Digit)에 일치

\s | 공백(space,tab)에 일치

(?=) | 앞쪽일치(Lookahead)

(?<=) | 뒤쪽일치(Lookbehind)

 

 

1.정규식표현 패턴(표현)

const str = `
010-1234-1234
themain@mail.com
https://www.naver.com
The buick brown fox jumps over the lazy dog
aaabbbccddd
http://localhost:1234
`;

//하단처럼 작성하면 null 출력 , d$의 끝부분을 예시의 마침 백틱기호로 인식
// console.log(str.match(/d$/g));

//console.log(str.match(/d$/gm));
//console.log(str.match(/^t/gim));
//console.log(str.match(/./g));
//console.log(str.match(/h..p/g));
//console.log(str.match(/fox|dog/g));
//console.log(str.match(/https?/g)) //https, http 검색
//console.log(str.match(/d{2}/));
//console.log(str.match(/d{2}/g));
//console.log(str.match(/d{2,}/g)); //dddd
console.log(str.match(/\b\w{2,3}\b/g)); // \w의 의미: 숫자를 포함한 영어알파벳 \b 는 경계
//두글자 이상 세글자 이하인 영문이나 숫자

2.정규식표현 패턴(표현)

const str = `
010-1234-1234
themain@mail.com
https://www.naver.com
The buick brown fox jumps over the lazy dog
aaabbbccddd
http://localhost:1234
`;

//console.log(str.match(/[가-힣]{1,}/g)) //한개 이상의 연속되는 모든 한글
console.log(str.match(/\bf\w{1,}\b/g));
//f로 시작하고 63개 문자가 1개 이상 일치+경계지정
// = 소문자 f로 시작하는 모든 영단어
//console.log(str.match(/\s/g)); //줄바꿈문자도 해당

//정규식표현으로 모든 공백 사라지게하기
const h = `    the hello world    ! 

`;
console.log(h.replace(/\s/g, ""));

3.정규식표현(패턴) 3 일치

const str = `
010-1234-1234
themain@mail.com
https://www.naver.com
The buick brown fox jumps over the lazy dog
aaabbbccddd
http://localhost:1234
`;

//1개이상 모든 문자,숫자중 @ 앞쪽일치
/*console.log(str.match(/.{1,}(?=@)/g) */
//1개이상 모든 문자,숫자중 @ 뒤쪽일치
console.log(str.match(/(?<=@).{1,}/g));