Tips/Java

[JAVA] 정규표현식 - URL

dextto™ 2013. 3. 15. 23:39

JAVA에서 URL 정규표현식을 알아보자. (발췌: http://goodidea.tistory.com/86)

 

원문에서는 마지막에 http://www.daum.net 과  같이 URL 마지막에 슬래쉬(/)가 없는 예에서는 에러가 난다.

이를 수정하면 아래와 같이 된다.

 

^(https?):\/\/([^:\/\s]+)(:([^\/]*))?((\/[^\s/\/]+)*)?\/?([^#\s\?]*)(\?([^#\s]*))?(#(\w*))?$

 

JAVA 테스트 코드로 바꾸면 다음과 같다.


    @Test

    public void url() {

        String regex = "^(https?):\\/\\/([^:\\/\\s]+)(:([^\\/]*))?((\\/[^\\s/\\/]+)*)?\\/?([^#\\s\\?]*)(\\?([^#\\s]*))?(#(\\w*))?$";

        Pattern p = Pattern.compile(regex);



        assertTrue(p.matcher("https://goodidea.tistory.com:8888/qr/aaa/ddd.html?abc=def&ddd=fgf#sharp").matches());

        assertTrue(p.matcher("http://dextto.tistory.com").matches());

        assertTrue(p.matcher("http://blog.daum.net/dexter").matches());

        assertTrue(p.matcher("http://www.daum.net:80/index.cfm").matches());

        assertTrue(p.matcher("http://xxx:password@www.daum.net").matches());

        assertTrue(p.matcher("http://localhost/index.php?ab=1&c=2").matches());

        assertTrue(p.matcher("http://localhost:8080").matches());

        assertTrue(p.matcher("http://dextto.tistory.com/admin/entry/post/?id=150&returnURL=/entry/JAVA-Regular-Expression-%EC%A0%95%EA%B7%9C-%ED%91%9C%ED%98%84%EC%8B%9D-%EC%98%88%EC%A0%9C").matches());

    }
반응형