Character Class & Assertions in Regular Expression 본문

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

Character Class & Assertions in Regular Expression

알 수 없는 사용자 2021. 6. 14. 02:26

Character Class

// Character Classes => 문자들을 구별하기 위해 사용됨
regExp = /\w/; // Word Character - 알파벳, 숫자, _
str = "_qwf";
const result1 = regExp.exec(str);
console.log(result1);

regExp = /\w+/; // + = 하나 또는 그 이상을 뜻함
str = "_qwf"; // +가 없는 결과와 비교해보자
const result2 = regExp.exec(str);
console.log(result2);

regExp = /\W/;  // Non Word Character - word character가 아닌 모든 것
str = "한글"; // true
const result3 = regExp.exec(str);
console.log(result3);

regExp = /\d/;  // any digit - 정수
str = "34"; // true
const result4 = regExp.exec(str);
console.log(result4);

regExp = /\D/;  // non digit - 정수가 아닌 모든 것
str = "34"; // false
str = "한글"; // true
const result5 = regExp.exec(str);
console.log(result5);

regExp = /\s/;  // whitespace - 공백
str = "34"; // false
str = " "; // true
const result6 = regExp.exec(str);
console.log(result6);

regExp = /\S/;  // whitespace - 공백이 아닌 모든 것
str = "34"; // true
str = " "; // false
const result7 = regExp.exec(str);
console.log(result7);

 

Assertions

// Assertions => 문장과 단어의 시작과 끝을 표현하거나 조건식을 포함한 패턴을 표현
regExp = /Hell\b/i; // word boundary = word character의 경계를 뜻함 (^, $와의 차이를 명확히 알자.)
str = "Hello Hell%";  // true
str = "Hello Hell_";  // false (_가 word character 이므로)
const result8 = regExp.exec(str);
console.log(result8);

regExp = /x(?=y)/;  // y가 뒤따르는 x를 검색
str = "2xy1"; // true
str = "2x y1" // false
const result9 = regExp.exec(str);
console.log(result9);

regExp = /x(?!y)/;  // y가 뒤따르지 않는 x를 검색
str = "2xy1"; // false
str = "2x y1" // true
const result10 = regExp.exec(str);
console.log(result10);

 

Comments