Introduction to regular expressions in Kotlin
suggest changeThis page shows how to use most of the functions in the Regex class, how null safety applies to those functions, and how raw strings make regex patterns easier to write and read.
The Regex class
To work with regular expressions in Kotlin, use the Regex(pattern: String) class and call functions such as find or replace on that object.
An example of the Regex class that returns true if the input string contains c or d:
val regex = Regex(pattern = "c|d")
val matched = regex.containsMatchIn(input = "abc") // matched: true
The result of every Regex function depends on matching the pattern against the input string. Some functions require a full match; the rest require only a partial match. containsMatchIn requires a partial match and is explained later on this page.
Null safety with regular expressions
Both find and matchEntire return a MatchResult?. The ? is how Kotlin represents a value that may be null. See null safety.
This example shows the result when find returns null:
val matchResult =
Regex("c|d").find("efg") // matchResult: null
val a = matchResult?.value // a: null
val b = matchResult?.value.orEmpty() // b: ""
a?.uppercase() // Still needs a question mark. => null
b.uppercase() // Called directly. => ""
With the orEmpty() function, b can’t be null and the ? character is unnecessary when you call functions on b.
If you don’t care about this safe handling of null values, Kotlin allows you to work with null values like in Java with the !! characters:
a!!.uppercase() // => NullPointerException
Raw strings in regex patterns
Kotlin provides an improvement over Java with a raw string that makes it possible to write pure regex patterns without double backslashes, that are necessary with a Java string. A raw string is represented with a triple quote:
"""\d{3}-\d{3}-\d{4}""" // raw Kotlin string
"\\d{3}-\\d{3}-\\d{4}" // standard Java string
find(input: CharSequence, startIndex: Int): MatchResult?
The input string will be matched against the pattern in the Regex object. It returns a MatchResult? with the first matched text at or after startIndex, or null if the pattern does not match. The result string is retrieved from the MatchResult? object’s value property. The startIndex parameter is optional with the default value 0.
To extract the first valid phone number from a string with contact details:
val phoneNumber :String? = Regex(pattern = """\d{3}-\d{3}-\d{4}""")
.find(input = "phone: 123-456-7890, e..")?.value // phoneNumber: 123-456-7890
With no valid phone number in the input string, the variable phoneNumber will be null.
findAll(input: CharSequence, startIndex: Int): Sequence<MatchResult>
Returns every match of the regex pattern in the input string.
To print out all numbers separated with space, from a text with letters and digits:
val matchedResults = Regex(pattern = """\d+""").findAll(input = "ab12cd34ef")
val result = StringBuilder()
for (matchedText in matchedResults) {
result.append(matchedText.value + " ")
}
println(result) // => 12 34
The matchedResults variable is a sequence with MatchResult objects. With an input string without digits, the findAll(..) function will return an empty sequence.
matchEntire(input: CharSequence): MatchResult?
If every character in the input string matches the regex pattern, the returned value equals input. Otherwise it is null.
Returns the input string if the whole input string is a number:
val a = Regex("""\d+""").matchEntire("100")?.value // a: 100
val b = Regex("""\d+""").matchEntire("100 dollars")?.value // b: null
matches(input: CharSequence): Boolean
Returns true if the whole input string matches the regex pattern. False otherwise.
Tests whether two strings contain only digits:
val regex = Regex(pattern = """\d+""")
regex.matches(input = "50") // => true
regex.matches(input = "50 dollars") // => false
containsMatchIn(input: CharSequence): Boolean
Returns true if part of the input string matches the regex pattern. False otherwise.
Tests whether two strings contain at least one digit:
Regex("""\d+""").containsMatchIn("50 dollars") // => true
Regex("""\d+""").containsMatchIn("Fifty dollars") // => false
split(input: CharSequence, limit: Int): List
Returns a new list without all the regex matches.
To return lists without digits:
val a = Regex("""\d+""").split("ab12cd34ef") // a: [ab, cd, ef]
val b = Regex("""\d+""").split("This is a test") // b: [This is a test]
There is one list element for each piece between matches. The first input string has two numbers, so the result has three elements.
replace(input: CharSequence, replacement: String): String
Replaces all matches of the regex pattern in the input string with the replacement string.
To replace all digits in a string with an x:
val result = Regex("""\d+""").replace("ab12cd34ef", "x") // result: abxcdxef