find
fun find(
input: CharSequence,
startIndex: Int = 0
): MatchResult?
fun find(input: CharSequence, startIndex: Int): MatchResult?
For JVM, JS, Native
Returns the first match of a regular expression in the input, beginning at the specified startIndex.
Parameters
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.
For Common
Returns the first match of a regular expression in the input, beginning at the specified startIndex.
fun main(args: Array<String>) {
//sampleStart
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)!!
println(match.value) // to be
println(match.range) // 0..4
val nextMatch = match.next()!!
println(nextMatch.range) // 13..17
val regex2 = "this".toRegex()
// If there is no matching string, then find method returns null
println(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".
println(regex3.find(inputString, 2)!!.range) // 13..17
//sampleEnd
}
Parameters
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.