RegExp

김민수·2023년 11월 16일
0
post-thumbnail

1. 정규 표현식이란?

정규 표현식 : 일정한 패턴을 가진 문자열의 집합을 표현하기 위해 사용하는 형식 언어다.
패턴 매칭 기능 : 특정 패턴과 일치하는 문자열을 검색하거나 추출 또는 치환할 수 있는 기능

  • 대부분의 프로그래밍 언어와 코드에디터에 내장되어 있다.
  • 문자열을 대상으로 패턴 매칭 기능을 제공한다.

2. 정규 표현식의 생성

정규 표현식 객체를 생성 방법

  • 정규 표현식 리터럴 : 일방적인 방법
const target = 'Is this all there is?';
const regexp = /is/i; // 패턴 : is , 플래그: i => 대소문자를 구별하지 않고 검색한다.
regexp.test(target);  //true
  • RegExp 생성자 함수
const target = 'Is this all there is?';
const regexp = new RegExp(/is/i);
regexp.test(target);  //true

3. RegExp 메서드

3개만 우선 보겠다.

RegExp.prototype.exec

  • 매칭 결과를 배열로 반환한다.
  • 없는 경우 null
  • /g를 써도 첫 번째 매칭 결과만 반환함
const target = 'Is this all there is?';
const regexp = /is/i; 
regexp.exec(target); // ['Is', index: 0, input: 'Is this all there is?', groups: undefined]

RegExp.prototype.test

  • 매칭 결과를 불리언 값으로 반환한다.
const target = 'Is this all there is?';
const regexp = /is/i; 
regexp.exec(target);
// true

String.prototype.match

  • 매칭 결과를 배열로 반환한다.
const target = 'Is this all there is?';

const regexp1 = /is/; 
const regexp2 = /is/g; 

target.match(regexp1); // ['is', index: 5, input: 'Is this all there is?', groups: undefined]
target.match(regexp2); // ['is', 'is']

4. 플래그

6개중 중요한 3개 플래그

플래그의미설명
iIgnore case대소문자를 구별하지 않고 패턴을 검색한다.
gGlobal대상 문자열 내에서 패턴과 일치하는 모든 문자열을 전역 검색한다.
mMulti line문자열의 행이 바뀌더라도 패턴 검색을 계속한다.
  • 옵션이므로 선택적 사용 가능.
  • 순서 상관없이 하나 이상의 플래그를 동시 사용 가능 ex) /ig

5. 패턴

정규 표현식은 패턴플래그로 구성된다.

패턴 : 문자열의 일정한 규칙을 표현하기 위해 사용한다.

  • /로 열고 닫으며, 따옴표를 포함하면 따옴표까지 패턴에 포함되어 검색된다.
  • 메타문자 또는 기호로 표현할 수 있다.

플래그 : 정규 표현식의 검색 방식을 설정하기 위해 사용한다.

문자열 검색

const target = 'Is this all there is?';

const regexp1 = /is/; 
const regexp2 = /is/g;
const regexp3 = /is/ig;

console.log(target.match(regexp1)); // ['is', index: 5, input: 'Is this all there is?', groups: undefined]
console.log(target.match(regexp2)); // ['is', 'is']
console.log(target.match(regexp3)); // ['is', 'is', 'is']

임의의 문자열 검색

const target = 'Is this all there is?';

// .은 임의의 문자 한 개를 의미한다.
const regexp = /.../g; 
console.log(target.match(regexp)); // ['Is ', 'thi', 's a', 'll ', 'the', 're ', 'is?']

반복 검색

const target = 'A AA B BB Aa Bb AAA color colour';

// {m, n}은 앞선 패턴이 최소 m번, 최대 n번 박복되는 문자열을 의미한다.
const regexp1 = /A{1,2}/g;
console.log(target.match(regexp1)); // ['A', 'AA', 'A', 'AA', 'A']

const regexp2 = /A{2}/g;
console.log(target.match(regexp2)); // ['AA', 'AA']

const regexp3 = /A{2,}/g;
console.log(target.match(regexp3)); // ['AA', 'AAA']

// +는 앞선 패턴이 최소 한번 이상 반복되는 문자열을 의미한다.
const regexp4 = /A+/g;
console.log(target.match(regexp4)); // ['A', 'AA', 'A', 'AAA']

// ?는 앞선 패턴이 최대 한 번(0번 포함) 이상 반복되는 문자열을 의미한다.
const regexp5 = /colou?r/g;
console.log(target.match(regexp5)); // ['color', 'colour']

OR 검색

const target = 'A AA B BB Aa Bb ZZ 12,345 _&*^';

// !은 or의 의미를 갖는다.
const regExp1 = /A|B/g;
console.log(target.match(regExp1)); // ['A', 'A', 'A', 'B', 'B', 'B', 'A', 'B']

// 분해되지 않은 단어 레벨로 검색하기 위해서는 A를 함께 사용한다.
const regExp2 = /A+|B+/g;
console.log(target.match(regExp2)); // ['A', 'AA', 'B', 'BB', 'A', 'B']

// 위의 예제의 축약. [] 내의 문자는 or로 동작한다. 그 뒤에 +를 사용하면 앞선 패턴을 한번 이상 반복한다.
const regExp3 = /[AB]+/g;
console.log(target.match(regExp3)); // ['A', 'AA', 'B', 'BB', 'A', 'B']

// 범위를 지정하려면 [] 내에 -를 사용한다.
const regExp4 = /[A-Z]+/g;
console.log(target.match(regExp4)); // ['A', 'AA', 'B', 'BB', 'A', 'B', 'ZZ']

// 대소문자를 구별하지 않고 알파벳을 검색하는 방법
const regExp5 = /[A-Za-z]+/g;
console.log(target.match(regExp5)); // ['A', 'AA', 'B', 'BB', 'Aa', 'Bb', 'ZZ']

// 숫자를 검색하는 방법
const regExp6 = /[0-9]+/g;
console.log(target.match(regExp6)); // ['12', '345']

// 쉼표를 패턴에 포함시키기
const regExp7 = /[0-9,]+/g;
console.log(target.match(regExp7)); // ['12,345']

// \d는 숫자를 의미한다. 
const regExp8 = /[\d,]+/g;
console.log(target.match(regExp8)); // ['12,345']

// \D는 문자를 의미한다.
const regExp9 = /[\D,]+/g;
console.log(target.match(regExp9)); // ['A AA B BB Aa Bb ZZ ', ',', ' _&*^']

// \w는 알파벳, 숫자, 언더스코어를 의미한다.
const regExp10 = /[\w,]+/g;
console.log(target.match(regExp10)); //  ['A', 'AA', 'B', 'BB', 'Aa', 'Bb', 'ZZ', '12,345', '_']

// \W는 알파벳, 숫자, 언더스코어가 아닌 문자를 의미한다.
const regExp11 = /[\W,]+/g;
console.log(target.match(regExp11)); //  [' ', ' ', ' ', ' ', ' ', ' ', ' ', ',', ' ', '&*^']

NOT 검색

const target = 'AA BB 12 Aa Bb'

// [...] 내의 ^은 not의 의미를 갖는다
const regExp = /[^0-9]+/g;
console.log(target.match(regExp)); // ['AA BB ', ' Aa Bb']

시작 위치로 검색

const target = 'https://google.com'

// [...] 밖의 ^은 문자열의 시작을 의미한다.
const regExp = /^https/;
console.log(regExp.test(target)); // true

마지막 위치로 검색

const target = 'https://google.com'

// $는 문자열의 마지막을 의미한다.
const regExp = /com$/;
console.log(regExp.test(target)); // true

6. 자주 사용하는 정규표현식

특정 단어로 시작하는 검색

const target = 'https://google.com';

// [...] 바깥의 ^은 문자열의 시작을 의미, ?은 앞선 패턴이 최대 한 번 이상 반복되는지 의미한다.
/^https?:\/\//.test(target); // true

특정 단어로 끝나는지 검사

const target = 'https://google.com';
/com$/.test(target); // true

숫자로만 이루어진 문자열인지 검사

const target = '123';
/^\d+$/.test(target); // true

하나 이상의 공백으로 시작하는지 검사

const target = ' a123';

// \s는 여러 가지 공백 문자를 의미한다.
/^[\s]+/.test(target); // true

아이디로 사용 가능한지 검사

const target = 'a123';
// 4 ~ 10자리 대소문자, 숫자
/^[A-Za-z0-9]{4,10}$/.test(target); // true

메일 주소 형식에 맞는지 검사

const target = 'test@gmail.com';
/^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/.test(target); // true

핸드폰 번호 형식에 맞는지 검사

const target = '010-1234-5678';
/^\d{3}-\d{3,4}-\d{4}$/.test(target); // true

특수 문자 포함 여부 검사

const target = 'abc#123';

// A-Za-z0-9 이외의 문자가 있는지 검사
(/[^A-Za-z0-9]/gi).test(target); // true

// 특수 문자 제거한다.
target.replace(/[^A-Za-z0-9]/gi, ''); // abc123

0개의 댓글