Regex in GWT to match URLs

后端 未结 3 1102
傲寒
傲寒 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:59

    You will have to use JSNI to do the regex evaluation part in Javascript. If you do write the regex with the escaped backslashes, that will get converted to Javascript as it is and will obviously be invalid. Thought it will work in the Hosted or Dev mode as thats still running Java bytecode, but not on the compiled application.

    A simple JSNI example to test if a given string is a valid URL:

    // Java method
    public native boolean isValidUrl(String url) /*-{
        var pattern = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
        return pattern.test(url);
    }-*/;
    

    There may be other irregularities between the Java and Javascript regex engines, so it's better to offload it completely to Javascript at least for moderately complex regexes.

提交回复
热议问题