正则表达式和GWT

lud*_*igm 81 java regex gwt

我的问题是:在GWT中使用正则表达式有一个很好的解决方案吗?

我对String.split(regex)的使用不满意.GWT将代码转换为JS,然后将正则表达式用作JS正则表达式.但我不能使用Java Matcher或Java Pattern之类的东西.但我需要这些用于组匹配.

有没有可能性或图书馆?

我尝试了Jakarta Regexp,但我遇到了其他问题,因为GWT不会模拟这个库使用的Java SDK的所有方法.

我希望能够在客户端使用这样的东西:

// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();

if (matchFound) {
    // Get all groups for this match
    for (int i=0; i<=matcher.groupCount(); i++) {
        String groupStr = matcher.group(i);
        System.out.println(groupStr);
    }
} 
Run Code Online (Sandbox Code Playgroud)

小智 95

使用RegExp的相同代码可能是:

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

if (matchFound) {
    // Get all groups for this match
    for (int i = 0; i < matcher.getGroupCount(); i++) {
        String groupStr = matcher.getGroup(i);
        System.out.println(groupStr);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你确定`<=`不应该是`<= matcher.getGroupCount()`中的``` (2认同)

Phi*_*oin 32

GWT 2.1现在有一个RegExp类可以解决你的问题:


Zbi*_*dro 19

这个答案涵盖了所有模式匹配,而不仅仅是一个,如此处的其他答案:

功能:

private ArrayList<String> getMatches(String input, String pattern) {
    ArrayList<String> matches = new ArrayList<String>();
    RegExp regExp = RegExp.compile(pattern, "g");
    for (MatchResult matcher = regExp.exec(input); matcher != null; matcher = regExp.exec(input)) {
       matches.add(matcher.getGroup(0));
    }
    return matches;
}
Run Code Online (Sandbox Code Playgroud)

......和样品使用:

ArrayList<String> matches = getMatches(someInputStr, "\\$\\{[A-Za-z_0-9]+\\}");
for (int i = 0; i < matches.size(); i++) {
    String match = matches.get(i);

}
Run Code Online (Sandbox Code Playgroud)

  • 你是完全正确的.这是拼图的缺失部分.10倍多! (3认同)