Metacharacters in JS RegExp, 정규표현식에서의 특수문자 본문

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

Metacharacters in JS RegExp, 정규표현식에서의 특수문자

알 수 없는 사용자 2021. 6. 12. 18:38

와일드 카드 역할을 하는 .과 *의 차이점과, 선택적인 문자검색을 할 수 있게 하는 ?의 정확한 이해에 주의하며 아래의 코드를 참조해주세요.

 

let regExp;

// literal charcters
regExp = /hello/i;

// Metacharacter Symbols 특수문자
regExp = /^hel/i; // ^ 뒤에 나오는 문자열로 시작하는 문자열만 검색
regExp = /orld$/i; // $ 앞에 나오는 문자열로 끝나는 문자열만 검색
regExp = /^hello$/i; // ^ 뒤에 나오는 문자열로 시작하고, $앞에 나오는 문자열로 끝나는 문자열만 검색
regExp = /h.o/i; // .에 해당하는 하나의 문자는 아무 값이나 들어가도 된다고 인식하고 검색 (ex. hlo)
regExp = /h*o/i; // *에 해당하는 0개 또는 그 이상의 아무 문자들은 아무 값이나 들어가도 된다고 인식하고 검색 (ex. hllo, hello,helllllo..)
regExp = /he?a?llo/i // ? 앞의 문자가 붙거나 아예 붙지 않는 문자열만 검색 (ex. hello, hallo, hllo)
regExp = /he?a?llo\?/i // 문자 앞에 \를 붙여서 해당 문자를 escape 할 수 있음.

// String to match
const str = "hllo world";

// log Results
const result = regExp.exec(str);
console.log(result);

function regExpTest(regExp, str) {
  if (regExp.test(str)) {
    console.log(`${str} matched ${regExp.source}`);
  } else {
    console.log(`${str} does not matched ${regExp.source}`);
  }
}

regExpTest(regExp, str);
Comments