GWT : how to get regex(Pattern and Matcher) working in client side

孤街醉人 提交于 2019-12-23 10:08:15

问题


We're using GWT 2.03 along with SmartGWT 2.2. I'm trying to match a regex like below in client side code.

Pattern pattern = Pattern.compile("\\\"(/\d+){4}\\\"");
String testString1 = "[    \"/2/4/5/6/8\",    \"/2/4/5/6\"]";
String testString2 = "[  ]";

Matcher matcher = pattern.matcher(testString1);
boolean result = false;
while (matcher.find()) {
    System.out.println(matcher.group());
}

It appears that Pattern and Matcher classes are NOT compiled to Javascript by the GWTC compiler and hence this application did NOT load. What is the equivalent GWT client code so that I can find regex matches within a String ?

How have you been able to match regexes within a String in client-side GWT ?

Thank you,


回答1:


Consider upgrading to GWT 2.1 and using RegExp.




回答2:


Just use the String class to do it! Like this:

String text = "google.com";
    if (text.matches("(\\w+\\.){1,2}[a-zA-Z]{2,4}"))
        System.out.println("match");
    else
        System.out.println("no match");

It works fine like this, without having to import or upgrade or whatever. Just change the text and regex to your liking.

Greetings, Glenn




回答3:


Use GWT JSNI to call native Javascript regexp:

public native String jsRegExp(String str, String regex)
/*-{
    return str.replace(/regex/);  // an example replace using regexp 
    }
}-*/;



回答4:


Perhaps you could download the RegExp files from GWT 2.1 and add them to your project?

http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/src/com/google/gwt/regexp/

Download GWT 2.1 incl source, add that directory somewhere in your project, then add the reference to the "RegExp.gwt.xml" using the <inherits> tag from your GWT XML.

I'm not sure if that would work, but it'd be worth a shot. Maybe it references something else GWT 2.1 specific which you don't have, but I've just checked out the code a bit and I don't think it does.




回答5:


GWT 2.1 now has a RegExp class that might solve your problem:

// Compile and use regular expression
RegExp regExp = RegExp.compile(patternStr);
MatchResult matcher = regExp.exec(inputStr);
boolean matchFound = regExp.test(inputStr);

if (matchFound) {
Window.alert("Match found");
    // Get all groups for this match
    for (int i=0; i<=matcher.getGroupCount(); i++) {
        String groupStr = matcher.getGroup(i);
        System.out.println(groupStr);
    }
}else{
Window.alert("Match not found");
}


来源:https://stackoverflow.com/questions/4158201/gwt-how-to-get-regexpattern-and-matcher-working-in-client-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!