有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javagwt:如何让regex(模式和匹配器)在客户端工作

我们正在使用GWT2.03和SmartGWT2.2。我试图在客户端代码中匹配下面这样的正则表达式

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());
}

GWTC编译器似乎没有将Pattern和Matcher类编译为Javascript,因此该应用程序没有加载。什么是等效的GWT客户机代码,以便在字符串中查找正则表达式匹配项

如何在客户端GWT中匹配字符串中的正则表达式

谢谢——


共 (5) 个答案

  1. # 1 楼答案

    使用GWT JSNI调用本机Javascript regexp:

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

    GWT2.1现在有一个RegExp类,可以解决您的问题:

    // 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");
    }
    
  3. # 3 楼答案

    考虑升级到GWT 2.1并使用^{}

  4. # 4 楼答案

    只要使用String类就可以了! 像这样:

    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");
    

    它可以像这样工作,无需导入或升级。 只需根据自己的喜好更改文本和正则表达式

    你好,格伦

  5. # 5 楼答案

    也许您可以从GWT2.1下载RegExp文件,并将其添加到您的项目中

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

    下载GWT 2.1 incl source,将该目录添加到项目中的某个位置,然后使用GWT xml中的<inherits>标记添加对“RegExp.GWT.xml”的引用

    我不确定这是否有效,但值得一试。也许它引用了GWT2.1中没有的特定代码,但我刚刚检查了一下代码,我认为它没有