正则表达式和 GWT

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

例如,我对 String.split (regex)的使用并不满意。GWT 将代码转换为 JS,然后将正则表达式用作 JS 正则表达式。但是我不能使用类似 JavaMatcher 或 Java 模式的东西。但是我需要这些来进行小组配对。

有没有可能或者图书馆?

我尝试使用 JakartaRegexp,但是遇到了其他问题,因为 GWT 没有模拟这个库使用的 JavaSDK 的所有方法。

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

// 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);
}
}
40520 次浏览

If you want a pure GWT solution, I'm not sure it can be done. But if you're willing to use JSNI, you can use JavaScript's RegExp object to get the matched groups and all. You'll need to learn JSNI for GWT and JavaScript RegExp object.

The GWTx library seems to provide an emulation of java.util.regex.Pattern and friends. It doesn't look complete (Matcher in particular), but might be a good start.

The technique they use to plug their own implementations of Java classes for the client side is the <super-source> declaration in module XML. It's mentioned in GWT docs, module XML format description under "Overriding one package implementation with another". Standard JRE translatable classes in GWT are emulated the same way.

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

The same code using RegExp could be:

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

This answer covers ALL pattern matches, not only one, as in other answers here:

Function:

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

...and sample use:

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


}