find
fun find(
input: CharSequence,
startIndex: Int = 0
): MatchResult?
(Common source) (JVM source) (Native source)
For Common, JVM, Native
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()
Exceptions
IndexOutOfBoundsException
- if startIndex is less than zero or greater than the length of the input char sequence.
Return An instance of MatchResult if match was found or null
otherwise.
For JS
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()
Exceptions
IndexOutOfBoundsException
- if startIndex is less than zero or greater than the length of the input char sequence.
Return An instance of MatchResult if match was found or null
otherwise.