代码之家  ›  专栏  ›  技术社区  ›  anjanb

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

  •  5
  • anjanb  · 技术社区  · 14 年前

    我们使用的是GWT 2.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编译器编译成Javascript,因此这个应用程序没有加载。什么是等效的GWT客户机代码,以便我可以在字符串中找到regex匹配项?

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

    谢谢您,

    5 回复  |  直到 14 年前
        1
  •  12
  •   Adrian Smith    8 年前

    考虑升级到GWT 2.1并使用 RegExp .

        2
  •  13
  •   glenn    14 年前

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

    它的工作原理是这样的,不需要导入或升级。 只需根据您的喜好更改文本和正则表达式。

    你好,格伦

        3
  •  5
  •   Peter Knego    14 年前

    使用 GWT JSNI 要调用本机Javascript regexp:

    public native String jsRegExp(String str, String regex)
    /*-{
        return str.replace(/regex/);  // an example replace using regexp 
        }
    }-*/;
    
        4
  •  2
  •   Adrian Smith    14 年前

    也许您可以从GWT 2.1下载RegExp文件并将其添加到您的项目中?

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

    下载GWT 2.1includsource,将该目录添加到项目中的某个位置,然后使用 <inherits> 来自GWT XML的标记。

    我不确定那是否可行,但值得一试。也许它引用了其他一些GWT 2.1特定的东西,但我刚刚签出了代码,我认为它没有。

        5
  •  2
  •   StackOverFlow    13 年前

    GWT 2.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");
    }