KT-20357 Add sample code for Regex.find
Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
This commit is contained in:
@@ -47,6 +47,7 @@ expect class Regex {
|
||||
*
|
||||
* @param startIndex An index to start search with, by default 0. Must be not less than zero and not greater than `input.length()`
|
||||
* @return An instance of [MatchResult] if match was found or `null` otherwise.
|
||||
* @sample samples.text.Regexps.find
|
||||
*/
|
||||
fun find(input: CharSequence, startIndex: Int = 0): MatchResult?
|
||||
|
||||
|
||||
@@ -22,4 +22,27 @@ class Regexps {
|
||||
// destructured group values only contain values of the groups, excluding the zeroth group.
|
||||
assertPrints(numberedGroupValues, "[John, 9731879]")
|
||||
}
|
||||
|
||||
@Sample
|
||||
fun find() {
|
||||
val inputString = "to be or not to be"
|
||||
val regex = "to \\w{2}".toRegex()
|
||||
// If there is matching string, then find method returns non-null MatchResult
|
||||
val match = regex.find(inputString)!!
|
||||
assertPrints(match.value, "to be")
|
||||
assertPrints(match.range, "0..4")
|
||||
|
||||
val nextMatch = match.next()!!
|
||||
assertPrints(nextMatch.range, "13..17")
|
||||
|
||||
val regex2 = "this".toRegex()
|
||||
// If there is no matching string, then find method returns null
|
||||
assertPrints(regex2.find(inputString), "null")
|
||||
|
||||
val regex3 = regex
|
||||
// to be or not to be
|
||||
// ^^^^^
|
||||
// Because the search starts from the index 2, it finds the last "to be".
|
||||
assertPrints(regex3.find(inputString, 2)!!.range, "13..17")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user