Removing redundant escape as per recommended by Android Studio cause app to crash

Viewed 202

I have regex as below

object MyRegtest {
    val TEST = Pattern.compile("\\{[^{}]+\\}")
}

Android Studio says I have a redundant escape.

After removing them as per recommended by Android Studio, it became as below

object MyRegtest {
    val TEST = Pattern.compile("\\{[^{}]+}")
}

It seems all good, as when I run my unit test it compiles and run fine. Note it compile fine before and after changes

    @Test
    fun addition_isCorrect() {
        val matcher = MyRegtest.TEST.matcher("2 matches {GoOd} and {GrEaT}, not {} to catch")
        while (matcher.find()) {
            println(matcher.group())
        }
    }

When compile and run the App (simple sample)

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val matcher = MyRegtest.TEST.matcher("2 matches {GoOd} and {GrEaT}, not {} to catch")
        while (matcher.find()) {
            Log.d("Testing", matcher.group())
        }
    }
}

It will crash

Caused by: java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 9
    \{[^{}]+}

If I put back the original regex, the compiles app, and test works fine.

Did I do something wrong, or is this a bug recommendation from Android Studio? Why is the recommended optimized regex only works on unit test, and crash on the app?

1 Answers

In Android regex, you need to escape the closing curly brace outside a character class, otherwise, the pattern becomes invalid (the Syntax error in regexp pattern error is shown then as expected).

The notification you get from the Android Studio is most likely based on Java regex flavor, where the } char does not have to be escaped outside a character class.

So, in this case, Android Studio is wrong when notifying of a "redundant escape", it is not redundant in Android regex context.

Related