Introduction
In this part, we are going to learn about Kotlin Regex and Java Interoperability. Those who are new to Kotlin and willing to learn, go through this article series starting here: Introduction to Kotlin.
Kotlin Regex
Regex is used to refer to a regular expression that is used to search a string or replace on regex object. To use it, we need to use Regex(pattern: String). To use that, we need Kotlin.regex.text package too.
Kotlin Regex Constructor
- Regex(pattern: String) - It will give string pattern.
- Regex(pattern: String, option: RegexOption) - It will give string pattern and single option.
- Regex(pattern: String, options: Set<RegexOption>) - It will give string pattern and set of give options.
Example
- fun main(args: Array < String > ) {
- val regex = ""
- "x([yz]+)a?"
- "".toRegex()
- val matched1 = regex.matches(input = "bcdp")
- val matched2 = regex.matches(input = "bcdbcd")
- val matched3 = regex.matches(input = "xyza")
- println(matched1)
- println(matched2)
- println(matched3)
- }
Output
false
false
true
Kotlin Regex Pattern
Regex patterns are given below.
- x|y - x or y
- xy - x followed by y
- [xyz]- x,y,z
- [x-z]- x to z
- [^x-z]- outside the range of x-z
- ^xyz- xyz at beginning of the line
- xyz$- xyz at end of line
- .- any single character
Java Interoperability
Kotlin code is interoperability with Java code. The Java code can be called from Kotlin code and Kotlin code is also called from Java code simultaneously.


Join the conversation! Your thoughts help the community grow.