Alexei
Alexei

Reputation: 15726

Can't replace text by matching group : ArrayIndexOutOfBoundsException: length=2; index=2

In my Kotlin project: I has text:

DATA: 30-11-19 

I need to extract only date.

I try this:

 private fun testDates() {
        val DATE_REGEXP = ".*?\\d{2}-\\d{2}-\\d{2}.*"
        val someText = "DATA: 30-11-19"
        if (DATE_REGEXP.toRegex().matches(someText)) {
            val replace = someText.replace(DATE_REGEXP.toRegex(), "$1");
            Debug.d(TAG, "testDates_replace = $replace")
        }
    }

But I get runtime error:

01-14 18:50:29.862 E/AndroidRuntime(31161): Caused by: java.lang.reflect.InvocationTargetException
01-14 18:50:29.862 E/AndroidRuntime(31161):     at java.lang.reflect.Constructor.newInstance(Native Method)
01-14 18:50:29.862 E/AndroidRuntime(31161):     at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
01-14 18:50:29.862 E/AndroidRuntime(31161):     ... 16 more
01-14 18:50:29.862 E/AndroidRuntime(31161): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
01-14 18:50:29.862 E/AndroidRuntime(31161):     at java.util.regex.Matcher.group(Matcher.java:579)
01-14 18:50:29.862 E/AndroidRuntime(31161):     at java.util.regex.Matcher.appendEvaluated(Matcher.java:138)
01-14 18:50:29.862 E/AndroidRuntime(31161):     at java.util.regex.Matcher.appendReplacement(Matcher.java:111)
01-14 18:50:29.862 E/AndroidRuntime(31161):     at java.util.regex.Matcher.replaceAll(Matcher.java:319)
01-14 18:50:29.862 E/AndroidRuntime(31161):     at kotlin.text.Regex.replace(Regex.kt:143)
01-14 18:50:29.862 E/AndroidRuntime(31161):     at com.myproject.testDates(ScanCheckViewModel.kt:817)
01-14 18:50:29.862 E/AndroidRuntime(31161):     at com.myproject.<init>(ScanCheckViewModel.kt:98)
01-14 18:50:29.862 E/AndroidRuntime(31161):     ... 18 more

Upvotes: 2

Views: 74

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

$1 represents the second group of match captured by () so you need to add a pair so use

.*?(\\d{2})-(\\d{2})-\\d{2}.*
   ^      ^

Note: By default $0 captures the whole match.

Upvotes: 2

Related Questions