regexp를 사용하여 문자열중 일부분 추출하는 방법 (정규식 추출)

 

 

Javascript

	// 그룹이용
    var str = `1등:홍길동, 2등:임꺽정.`;
    var rx = /.+:(.+), .+:(.+)$/;
    var arr = rx.exec(str); //   1: "홍길동" ,  2: "임꺽정."
   

    // 이중 그룹 이용
    // 마지막에 위치한 js 파일 이름 추출하기
    var str = "https://www.example.com/test/app1.js?v=qwe:8:1";
    var arr = /.+(\/(\w+)\..+)$/.exec(str); // 1: "/app1.js?v=qwe:8:1"     2: "app1"
    // 참고 : 마지막 찾기 /.+(\/.+)$   ==  "/app1.js?v=qwe:8:1"

 

//-----------------------------------------------------------------------------

php

        $str = '1등:홍길동, 2등:임꺽정.';
        preg_match('/.+:(.+), .+:(.+)$/', $str, $matches);

        // 이중 그룹 이용
        // 마지막에 위치한 js 파일 이름 추출하기
        $str = "https://www.example.com/test/app1.js?v=qwe:8:1";
        preg_match('/.+(\/(\w+)\..+)$/', $str, $matches);

 

 

반응형
Posted by codens