📜  Kotlin正则表达式简介

📅  最后修改于: 2021-01-05 08:12:06             🧑  作者: Mango

Kotlin正则表达式

正则表达式通常是指用于搜索字符串或替换正则表达式对象的正则表达式。要使用它的功能,我们需要使用Regex(pattern:String)类。 Kotlin的Regex类可在kotlin.text.regex包中找到。

Kotlin Regex构造函数

Regex(pattern: String) It creates a regular expression from the given string pattern.
Regex(pattern: String, option: RegexOption) It creates a regular expression from the given string pattern and given single option.
Regex(pattern: String, options: Set) It creates a regular expression from the given string pattern and set of given options.

正则表达式功能

Functions Descriptions
fun containsMatchIn(input: CharSequence): Boolean It indicates that regular expression contains at least one input character
fun find(
input: CharSequence,

startIndex: Int = 0
): MatchResult?
It returns the first match of regular expression in the input character sequence, begins from given startIndex.
fun findAll(

input: CharSequence,

startIndex: Int = 0

): Sequence
It returns all occurrences of regular expression in the input string, starts from the given startIndex.
funmatchEntire(input: CharSequence): MatchResult? It is used to match complete input character from the pattern.
infix fun matches(input: CharSequence): Boolean It indicates whether all input character sequence matches in regular expression.
fun replace(input: CharSequence, replacement: String): String It replaces all the input character sequence of regular expression with given replacement string.
fun replaceFirst(
input: CharSequence,
replacement: String
): String
It replaces the first occurrence of regular expression in the given input string with given replacement string.
fun split(input: CharSequence, limit: Int = 0): List It splits the input character sequence of regular expression.
fun toPattern(): Pattern
fun toString(): String
It returns the regular expression in string.

Regex类检查示例包含输入模式

fun main(args: Array){
val regex = Regex(pattern = "ko")
val matched = regex.containsMatchIn(input = "kotlin")
println(matched)
}

输出:

true

Regex函数的结果基于匹配的regex模式和输入字符串。一些函数检查部分匹配,而某些功能检查完全匹配。

containsMatchIn()的正则表达式示例

fun main(args: Array){

val regex = """a([bc]+)d?""".toRegex()
val matched = regex.containsMatchIn(input = "xabcdy")
println(matched)

}

输出:

true

匹配的正则表达式示例(输入:CharSequence):布尔值

matchs(input:CharSequence):regex布尔函数会检查所有输入字符序列是否匹配正则表达式。

fun main(args: Array){

val regex = """a([bc]+)d?""".toRegex()
val matched1 = regex.matches(input = "xabcdy")
val matched2 = regex.matches(input = "xabcdyabcd")
val matched3 = regex.matches(input = "abcd")
println(matched1)
println(matched2)
println(matched3)
}

输出:

false
false
true

matchEntire(输入:CharSequence)的正则表达式示例:MatchResult?

matchEntire()函数用于匹配模式中的完整输入字符。

fun main(args: Array){

val regex = Regex("abcd")
val matchResult1 = regex.matchEntire("abcd")?.value
val matchResult2 = regex.matchEntire("abcda")?.value

val matchResult3 = Regex("""\d+""").matchEntire("100")?.value  
val matchResult4 = Regex("""\d+""").matchEntire("100 dollars")?.value

println(matchResult1)
println(matchResult2)
println(matchResult3)
println(matchResult4)
}

输出:

abcd
null
100
null

正则表达式示例offind(输入:CharSequence,startIndex:Int = 0):MatchResult?

find函数用于从正则表达式对象中查找输入字符序列。

fun main(args: Array){

val emailParttern = Regex("""\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}""")
val email :String? = emailParttern.find("this is my email mymail@google.com")?.value
println(email)
val phoneNumber :String? = Regex(pattern = """\d{3}-\d{3}-\d{4}""")
            .find("phone: 123-456-7890, e..")?.value 
println(phoneNumber)
}

输出:

mymail@google.com
123-456-7890

正则表达式示例offindAll(input:CharSequence,startIndex:Int = 0):序列

正则表达式的findAll()函数根据提供的模式返回匹配结果的序列。

fun main(args: Array){
val foundResults = Regex("""\d+""").findAll("ab12cd34ef 56gh7 8i")
val result = StringBuilder()
    for (findText in foundResults) {
result.append(findText.value + " ")
    }
println(result)
}

输出:

12 34 56 7 8

替换的正则表达式示例(输入:CharSequence,替换:String):String

Regex replace()函数用指定的替换字符串替换输入字符序列中的所有匹配模式。

fun main(args: Array){
val replaceWith = Regex("beautiful")
val resultString = replaceWith.replace("this picture is beautiful","awesome")
println(resultString)
}

输出:

this picture is awesome

正则表达式ofreplaceFirst(输入:CharSequence,替换:字符串):字符串

Regex replaceFirst()函数用指定的替换字符串替换输入字符序列中匹配模式的第一个匹配项。

fun main(args: Array){
val replaceWith = Regex("beautiful")
val resultString = replaceWith.replaceFirst("nature is beautiful, beautiful is nature","awesome")
println(resultString)
}

输出:

nature is awesome, beautiful is nature

正则表达式示例split(输入:CharSequence,限制:Int = 0):列表

regex split()函数根据提供的模式拆分输入字符序列。此拆分值在列表中返回。

fun main(args: Array){
val splitedValue = Regex("""\d+""").split("ab12cd34ef")
val nonsplited= Regex("""\d+""").split("nothing match to split" )
println(splitedValue)
println(nonsplited)
}

输出:

[ab, cd, ef]
[nothing match to split]