欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Kotlin語言編程Regex正則表達(dá)式實(shí)例詳解

 更新時(shí)間:2022年08月29日 16:18:20   作者:子不語Any  
這篇文章主要為大家介紹了Kotlin語言編程Regex正則表達(dá)式實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

前言

回想一下,在學(xué)Java時(shí)接觸的正則表達(dá)式,其實(shí)Kotlin中也是類似。只不過使用Kotlin 的語法來表達(dá),更為簡(jiǎn)潔。正則(Regex)用于搜索字符串或替換正則表達(dá)式對(duì)象,需要使用Regex(pattern:String)類。 在Kotlin中 Regex 是在 kotlin.text.regex 包。

Regex 構(gòu)造函數(shù)

構(gòu)造函數(shù)描述
Regex(pattern: String)給定的字符串模式創(chuàng)建正則式。
Regex(pattern: String, option: RegexOption)給定的字符串模式創(chuàng)建一個(gè)正則式并給出單個(gè)選項(xiàng)
Regex(pattern: String, options: Set<RegexOption>)給定的字符串模式和給定選項(xiàng)集創(chuàng)建正則表達(dá)式

常用正則表達(dá)方法

方法描述
fun containsMatchIn(input: CharSequence): Boolean包含至少一個(gè)輸入字符
fun find(input: CharSequence, startIndex: Int = 0): MatchResult?返回輸入字符序列中正則表達(dá)式的第一個(gè)匹配項(xiàng),從給定的startIndex開始
fun findAll(input: CharSequence, startIndex: Int = 0): Sequence<MatchResult>返回輸入字符串中所有出現(xiàn)的正則表達(dá)式,從給定的startIndex開始
fun matchEntire(input: CharSequence): MatchResult?用于匹配模式中的完整輸入字符
fun matches(input: CharSequence): Boolean輸入字符序列是否與正則表達(dá)式匹配
fun replace(input: CharSequence, replacement: String): String用給定的替換字符串替換正則表達(dá)式的所有輸入字符序列

示例展示

這里通過調(diào)用幾個(gè)常見正則函數(shù)進(jìn)行幾組數(shù)據(jù)查找,展示常用正則表達(dá)式用法:

1.containsMatchIn(input: CharSequence) 包含指定字符串

使用場(chǎng)景:判定是否包含某個(gè)字符串

val regex = Regex(pattern = "Kot")
val matched = regex.containsMatchIn(input = "Kotlin")
運(yùn)行結(jié)果:
matched = true

2.matches(input: CharSequence) 匹配字符串

使用場(chǎng)景:匹配目標(biāo)字符串

val regex = """a([bc]+)d?""".toRegex()
val matched1 = regex.matches(input = "xabcdy")
val matched2 = regex.matches(input = "abcd")
運(yùn)行結(jié)果:
matched1 = false
matched2 = true

3.find(input: CharSequence, startIndex: Int = 0) 查找字符串,并返回第一次出現(xiàn)

使用場(chǎng)景:返回首次出現(xiàn)指定字符串

val phoneNumber :String? = Regex(pattern = """\d{3}-\d{3}-\d{4}""")
.find("phone: 123-456-7890, e..")?.value
結(jié)果打印:
123-456-7890

4.findAll(input: CharSequence, startIndex: Int = 0) 查找字符串,返回所有出現(xiàn)的次數(shù)

使用場(chǎng)景:返回所有情況出現(xiàn)目標(biāo)字符串

val foundResults = Regex("""\d+""").findAll("ab12cd34ef 56gh7 8i")
val result = StringBuilder()
for (text in foundResults) {
    result.append(text.value + " ")
}
運(yùn)行結(jié)果:
12 34 56 7 8

5.replace(input: CharSequence, replacement: String) 替換字符串

使用場(chǎng)景:將指定某個(gè)字符串替換成目標(biāo)字符串

val replaceWith = Regex("beautiful")
val resultString = replaceWith.replace("this picture is beautiful","awesome")
運(yùn)行結(jié)果:
this picture is awesome

總結(jié)

通過Kotlin中封裝好的正則函數(shù)表達(dá)式,按規(guī)定語法形式傳入待查字符串?dāng)?shù)據(jù)以及規(guī)則就可以很高效獲取到目標(biāo)數(shù)據(jù),它最大的功能就是在于此??梢耘cJava中的正則形式類比,會(huì)掌握的更牢固。

以上就是Kotlin語言編程Regex正則表達(dá)式實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于Kotlin Regex正則表達(dá)式的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論