diff --git a/libraries/stdlib/src/kotlin/text/StringsJVM.kt b/libraries/stdlib/src/kotlin/text/StringsJVM.kt index 6184514bba6..8e4fc1a996e 100644 --- a/libraries/stdlib/src/kotlin/text/StringsJVM.kt +++ b/libraries/stdlib/src/kotlin/text/StringsJVM.kt @@ -120,8 +120,14 @@ public fun String.format(locale: Locale, vararg args : Any?) : String = java.lan /** * Splits this string around matches of the given regular expression. + + * @param limit The maximum number of substrings to return. Zero by default means no limit is set. */ -public fun String.split(regex: Pattern, limit: Int = 0): List = regex.split(this, limit).asList() +public fun String.split(regex: Pattern, limit: Int = 0): List +{ + require(limit >= 0, { "Limit must be non-negative, but was $limit" } ) + return regex.split(this, if (limit == 0) -1 else limit).asList() +} /** * Returns a substring of this string starting with the specified index. diff --git a/libraries/stdlib/test/text/StringJVMTest.kt b/libraries/stdlib/test/text/StringJVMTest.kt index 93b4dac2015..679c1a8e5f0 100644 --- a/libraries/stdlib/test/text/StringJVMTest.kt +++ b/libraries/stdlib/test/text/StringJVMTest.kt @@ -59,6 +59,17 @@ class StringJVMTest { assertEquals(s, list[0]) } + test fun testSplitByPattern() { + val s = "ab1cd2def3" + val isDigit = "\\d".toRegex() + assertEquals(listOf("ab", "cd", "def", ""), s.split(isDigit)) + assertEquals(listOf("ab", "cd", "def3"), s.split(isDigit, 3)) + + fails { + s.split(isDigit, -1) + } + } + test fun repeat() { fails{ "foo".repeat(-1) } assertEquals("", "foo".repeat(0))