TIL. NO7. JAVASCRIPT(5)

유자탱자🍋·2021년 1월 26일

1. 정규표현식 (regular expression)

참고)
정규표현식을 시각화
정규표현식 빌더

정규표현식(regular expression)은 문자열에서 특정한 문자를 찾아내는 도구다.

필요한 정보를 추출하는 것, 확인하고자 하는 정보의 유무를 테스트하는 것, 검색된 정보를 다른 정보로 치환하는 것

1) 컴파일(compile)
검출하고자 하는 패턴을 만드는 일

  • 정규표현식 리터럴
    var pattern = /a/
  • 정규표현식 객체 생성자
    var pattern = new RegExp('a');

2) 실행(execution)

  • RegExp.exec() → 추출

    console.log(pattern.exec('abcdef')); // ["a"]
    
    console.log(pattern.exec('bcdefg')); // null
  • RegExp.test() → 테스트

    console.log(pattern.test('abcdef')); // true
    
    cnosole.log(pattern.test('bcdefg')); // false
  • String.match() → 추출

    var str = 'abcdef'
    str.match(pattern); // ["a"]
  • String.replace() → 치환

    var str = 'abcdef'
    str.replace(pattern, 'A'); // Abcdef

3) 옵션

  • i : i를 붙이면 대소문자를 구분하지 않는다.
    var pattern = /a/i;
    'Abcde'.match(pattern)); // ["A"]
  • g: g를 붙이면 검색된 모든 결과를 리턴한다.
    var pattern = /a/g;
    'abcdea'.match(pattern)); // ["a", "a"]

4) 치환

  • $(캡쳐) : 그룹을 지정하고 지정된 그룹을 사용하는 기능

    var pattern = /(\w+)\s(\w+)/;
    var str = "coding everybody";
    var result = str.replace(pattern, "$2, $1");
    console.log(result); // everybody, coding
    

0개의 댓글