Regex in GWT to match URLs

后端 未结 3 1213
傲寒
傲寒 2021-01-03 10:10

I implemented the Pattern class as shown here: http://www.java2s.com/Code/Java/GWT/ImplementjavautilregexPatternwithJavascriptRegExpobject.htm

And I would like to us

3条回答
  •  忘掉有多难
    2021-01-03 10:54

    I don't know exactly how this would help but here is the exact function you requested in Javascript. I guess using JSNI like Anurag said will help.

    var urlPattern = "(https?|ftp)://(www\\.)?(((([a-zA-Z0-9.-]+\\.){1,}[a-zA-Z]{2,4}|localhost))|((\\d{1,3}\\.){3}(\\d{1,3})))(:(\\d+))?(/([a-zA-Z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?(\\?([a-zA-Z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*)?(#([a-zA-Z0-9._-]|%[0-9A-F]{2})*)?";
    
    function isValidURL(url) {
    
        urlPattern = "^" + urlPattern + "$";
        var regex = new RegExp(urlPattern);
    
        return regex.test(url);
    
    }
    

    Like what @S.Mark said, I basically took the "java" way of doing Regular Expression in Javascript.

    In Java, you would just done it the following way (see how the expression is the same).

    String urlPattern = "(https?|ftp)://(www\\.)?(((([a-zA-Z0-9.-]+\\.){1,}[a-zA-Z]{2,4}|localhost))|((\\d{1,3}\\.){3}(\\d{1,3})))(:(\\d+))?(/([a-zA-Z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?(\\?([a-zA-Z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*)?(#([a-zA-Z0-9._-]|%[0-9A-F]{2})*)?";
    

    Hope this helps. PS, this Regular expression works and even validates sites pointing to localhost:port) where port is any digit port number.

提交回复
热议问题