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?