Character Sets, Quantifier and Grouping in Regular Expression, 정규표현식에서의 문자열 집합, 수량자 그리고 그룹화 본문

2021 프론트 엔드 로드맵 따라가기/JS

Character Sets, Quantifier and Grouping in Regular Expression, 정규표현식에서의 문자열 집합, 수량자 그리고 그룹화

알 수 없는 사용자 2021. 6. 13. 01:22

수량자를 이용할 때 ^와 $ 특수문자를 적절히 섞어써야할 때가 있음에 주의하면서 아래의 코드를 살펴보아요. (해당 부분은 그룹핑 코드에 표기해놓았습니다)

 

Character Sets

// Character Sets
// brackets [] - 대괄호로 감싸져있는 문자들은 무엇이든 검색되도록 한다. ? 특수문자와는 다르게 알맞은 문자가 존재하지 않는 경우 검색되지 않는다.
regExp = /gr[ae]y/i;  // 대괄호 안에 위치한 문자는 a나 e여야한다.
str = "gray"; // true
str = "grey"; // true
str = "gry";  // false
const result1 = regExp.exec(str);
console.log(result1);

regExp = /[^GP]ray/i; // 대괄호 안에 위치한 문자들은 g나 p가 아니여야한다. 괄호 밖에서 쓰일 때랑 헷갈리지 말자.
str = "gray"; // false
str = "pray"; // false
str = "xray"; // true
const result2 = regExp.exec(str);
console.log(result2);

regExp = /[A-Z]ray/i; // -(dash)를 이용해 범위를 정할 수 있다.
str = "aray"; // true
str = "cray"; // true
str = "0ray"; // false
const result3 = regExp.exec(str);
console.log(result3);

regExp = /[A-Za-z]ray/; // i플래그 없이 대소문자 무관처리를 할 수도 있다.
str = "aray"; // true
str = "Aray"; // true
const result4 = regExp.exec(str);
console.log(result4);

 

Quantifier

// Quantifier
// Braces {} - 중괄호 안에 위치한 숫자만큼 중괄호 왼쪽의 문자가 존재하는 문자열 검색한다.
regExp = /Ar{2}ay/i;
str = "Array";  // true
str = "Aray"; // false
const result5 = regExp.exec(str);
console.log(result5);

regExp = /Ar{2,5}ay/i;  //  r이 2개부터 5개까지 존재할 수 있다.
str = "Array";  // true
str = "Arrrrray";  // true
str = "Arrrrrray";  // false
const result6 = regExp.exec(str);
console.log(result6);

regExp = /Ar{2,}ay/i;  //  r이 최소 2개부터 무한하게 존재할 수 있다.
str = "Array";  // true
str = "Arrrrray";  // true
str = "Aray";  // false
const result7 = regExp.exec(str);
console.log(result7);

 

Grouping

 

// Grouping
// Parentheses () - 소괄호는 해당 표현식을 그룹화할 수 있다.
regExp = /[a-z][0-9]{3}/i;  // a-z 중 문자하나와 0-9 중 숫자 셋
regExp = /([a-z][0-9]){3}/i;  // a-z 중 문자하나와 0-9 중 숫자 하나씩 셋  (위와의 차이를 주목)
str = "a0b1c2"; // true
/*
  아래의 문자열은 수량자를 사용할 때 ^와 $를 적절히 섞어써야하는 경우가 존재하는 문자열이다.
  해당 문자열 중에 위의 표현식에 맞는 문자열이 존재하기 때문이다.
  따라서 포함이 아닌 제한의 개념으로 접근하려면
  regExp = /^([a-z][0-9]){3}$/i;
  를 사용해야한다.
*/
str = "a0b1c2d3"; // true
str = "a000b111c222"  // false
str = "a000"  // false
const result8 = regExp.exec(str);
console.log(result8);

 

Comments