String.split(Pattern, limit) now treats limit differently: 0 means no limit is specified, but trailing empty elements are not stripped; -1 and other negative values are not allowed.
This commit is contained in:
@@ -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.
|
* 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<String> = regex.split(this, limit).asList()
|
public fun String.split(regex: Pattern, limit: Int = 0): List<String>
|
||||||
|
{
|
||||||
|
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.
|
* Returns a substring of this string starting with the specified index.
|
||||||
|
|||||||
@@ -59,6 +59,17 @@ class StringJVMTest {
|
|||||||
assertEquals(s, list[0])
|
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() {
|
test fun repeat() {
|
||||||
fails{ "foo".repeat(-1) }
|
fails{ "foo".repeat(-1) }
|
||||||
assertEquals("", "foo".repeat(0))
|
assertEquals("", "foo".repeat(0))
|
||||||
|
|||||||
Reference in New Issue
Block a user