Nice programing

정규식과 GWT

nicepro 2020. 10. 7. 08:16
반응형

정규식과 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);
    }
} 

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

GWT 2.1에는 이제 RegExp문제를 해결할 수 있는 클래스가 있습니다.


이 답변은 여기 다른 답변에서와 같이 하나뿐만 아니라 모든 패턴 일치를 다룹니다.

함수:

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

... 및 샘플 사용 :

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

}

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.

참고URL : https://stackoverflow.com/questions/1162240/regular-expressions-and-gwt

반응형