Regex does not work in Android, but works fine in Java

I have the following code:

String compact =  Pattern.compile(" *(\\{) *| *(\\}) *").matcher(" { { } } ")
                     .replaceAll("$1$2");

In Java it compactcontains {{}}- this is what I want - but on Android, I get {null{nullnull}null}what makes me crazy. Am I doing something wrong?

The following line gives the same result on Android:

String compact =  " { { } } ".replaceAll(" *(\\{) *| *(\\}) *", "$1$2")

Here is the online version of Java for those who want to play with it.

If this helps, I am going to Android SDK 23 with jdk1.7.0_79 on a Mac in Android Studio.

Update: Use "\\s*(\\{)\\s*|\\s*(\\})\\s*"has the same effect.

+4
source share
1 answer

, Java, , Android. Java, .

Matcher#replaceAll(String), , find(), , , String, .

.

, , . , (. Matcher#appendEvaluated(StringBuffer, String)) append(String) StringBuffer, .

group(int). Java, Android , null, , . : , , , , . , group(int) find().

, StringBuffer "null" String ( "null" ) null. , , , , "null" .

, Java, replaceAll.

(, SO 3 ), , Android , , , Java, replaceAll:

String input = " { { } } ";
Matcher matcher = Pattern.compile(" *(\\{) *| *(\\}) *").matcher(input);
while (matcher.find()) {
    String a = matcher.group(1); // $1
    String b = matcher.group(2); // $2
    String replacement = null;
    if (a != null && b != null) {
        replacement = a + b;
    } else if (a != null) {
        replacement = a;
    } else if (b != null) {
        replacement = b;
    }
    if (replacement != null) {
        input = input.replace(matcher.group(), replacement);
    }
}

, . ( 3 AM ).

0

Source: https://habr.com/ru/post/1619589/


All Articles