How to use javascript's regular expression by jsni?

267 views Asked by At

Same question has been asked here: How to pass a regular expression as a function parameter, but I can't get it work by JSNI.

This is the string of the regular expression that will be used to test email:

 "^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$"

and if putting it to firebug execute like this:

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$"/.test("[email protected]")

it will give what I want,but If wrapping it to a JSNI method:

 private native String reEmail()/-*{
      return "^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$";
 }-*/;

then passing it to the function:

private native boolean validate(String value, String regexp)/-*{
    //escape special characters
   var re=regexp.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').replace(/\x08/g, '\\x08');
    return new RegExp(re,'g').test(value)
}-*/;

like this:

 validate("[email protected]",reEmail());

It will give me false.Please tell what mistakes I have made,thanks.

1

There are 1 answers

0
Manolo Carrasco Moñino On BEST ANSWER

Why do you want to use JSNI for regular expressions?. Gwt already has classes to deal with them.

I would use com.google.gwt.regexp.shared.Regexp that features like Javascript's RegExp.

Using gwt com.google.gwt.regexp.shared.RegExp you have many advantages:

  • don't have to deal with JSNI, saving syntax errors.
  • make your code testable since RegExp can be used in JVM.
  • let the implementation escape strings or whatever.
  • performance would be the same

Your code could be like:

// Note that you have to double escape \
RegExp r = RegExp.compile("^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$");
if (r.test("[email protected]")) {

} else {

}

Anyway if you continue wanting to do in your way, to make your code work, you should escape your string before returning to java instead of in the place you are trying to do, also your JSNI block syntax is incorrect, note /*-{}-*/ instead of /-*{}*-/. And you don't need the 'g' flag.

validate("[email protected]",reEmail());

private native String reEmail() /*-{
    return "^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
}-*/;

private native boolean validate(String value, String regexp)/*-{
    return new RegExp(regexp).test(value)
}-*/;