정규표현식은 문자열에서 특정한 문자를 찾아내는 도구로써, 수십줄이 필요한 작업을 한줄로 끝낼 수 있다.

  - 정규표현식 생성 : 컴파일, 실행 두단계로 이뤄진다.

    * 컴파일 : 검출하고자 하는 패턴을 만드는일. 보통 리터럴과 객체생성자로 생성한다.
    * 정규표현식 리터럴

      예시

        ~ var pattern = /a/;

    * 정규표현식 객체 생성자

      예시

        ~ var pattern = new RegExp('a');

 

  - 정규표현식 메소드 실행

    * RegExp.exec() : 정규표현식에 해당하는 결과가 있으면 결과값 출력하고, 없으면 null을 return한다.
     예시
        ~ console.log(pattern.exec('abcdef'));  // 결과 : ["a"]
        ~ console.log(pattern.exec('bcdefg'));  // 결과 : null

 


    * RegExp.test() : 정규표현식에 해당하는 결과가 있으면 true를, 없으면 false를 return한다.
      예시
        ~ console.log(pattern.test('abcdef'));  // 결과 : true
        ~ console.log(pattern.test('bcdefg'));  // 결과 : false

 

 

  - 문자열 메소드 실행

    * String.match() : RegExp.exec()와 비슷

       예시

        ~ console.log('abcdef'.match(pattern));  // 결과 : ["a"]
        ~ console.log('bcdefg'.match(pattern));  // 결과 : null

 

 


    * String.replace() :  패턴으로 검색해서 변경한 후 변경된 값을 리턴
       예시

        ~ console.log('abcdef'.replace(pattern,'A'));  // 결과 : Abcdef

 

 

  - 옵션

    * i : i를 붙이면 대소문자를 구분하지 않는다.

      예시

        ~ var xi = /a/;
           console.log("Abcde".match(xi));  // 결과 : null
        ~ var oi = /a/i;
           console.log("Abcde".match(oi));  // 결과 : ["A"]

 

 

    * g : g를 붙이면 검색된 모든 결과를 리턴

      예시

        ~ var xg = /a/;
           console.log("abcdea".match(xg));  // 결과 : ["a"]

        ~ var og = /a/g
           console.log("abcdea".match(og));  // 결과 : ["a", "a"]

 

 

  - 캡처 : 괄호안의 패턴은 마치 변수처럼 재사용할 수 있다. 이때 $기호를 사용한다.

    예시

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

 

 

pattern에서 /(\w+)\s(\w+)/;를 이용해서 패턴을 작성했다. 앞 뒤로 단어가 있는 패턴을 찾는 정규표현식이다. 그리고 str 변수에 coding everybody 문장을 넣고 result 변수에 replace 함수를 이용하여 coding을 $1, everybody가 $2인 coding everybody 문장의 단어 순서를 바꾸고 ,를 넣었다. 바꿔서 출력한 결과 everybody, coding이 출력되었다.

 

  - 치환 : 패턴을 이용하여 변수 내용을 바꾼다.

    예시

      * var urlPattern = /\b(?:https?):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*/gim;
        var content = '네이버 : https://www.naver.com 입니다. 다음 :

        https://www.daum.net 입니다. ';
        var result = content.replace(urlPattern, function(url){
            return '<a href="'+url+'">'+url+'</a>';
        });
        console.log(result);

 

urlPattern 변수에 url을 찾는 정규표현식을 넣었다. 그리고 content에 네이버와 다음을 알려주는 url을 넣었다. 마지막으로 result에 replace 함수를 이용하여 url들(https//www.naver.com, https://www.daum.net)를 찾아서 기존 url에 <a href="url">url</a>을 추가하여 리턴한다. 그러므로 result 변수에 네이버 : <a href="https://www.naver.com">https://www.naver.com</a> 입니다. 다음 : <a href="https://www.daum.net">https://www.daum.net</a> 입니다. 가 저장되어 출력된다.

'Programming > 정규표현식' 카테고리의 다른 글

정규표현식 패턴들  (0) 2017.12.22
블로그 이미지

꼴통보안인

,