<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Kotlin 正則表達式 > 原文: [http://zetcode.com/kotlin/regularexpressions/](http://zetcode.com/kotlin/regularexpressions/) Kotlin 正則表達式教程展示了如何在 Kotlin 中使用正則表達式。 正則表達式用于文本搜索和更高級的文本操作。 正則表達式是內置工具,如`grep`,`sed`,文本編輯器(如 vi,emacs)以及包括 Kotlin,JavaScript,Perl 和 Python 在內的編程語言。 ## Kotlin 正則表達式 在 Kotlin 中,我們使用`Regex`構建正則表達式。 ```kt Regex("book") "book".toRegex() Regex.fromLiteral("book") ``` 模式是一個正則表達式,用于定義我們正在搜索或操縱的文本。 它由文本文字和元字符組成。 元字符是控制正則表達式計算方式的特殊字符。 例如,使用`\s`,我們搜索空白。 特殊字符必須雙轉義,否則我們可以使用 Kotlin 原始字符串。 創建模式后,可以使用其中一個函數將模式應用于文本字符串。 函數包括`matches()`,`containsMatchIn()`,`find()`,`findall()`,`replace()`和`split()`。 下表顯示了一些常用的正則表達式: | 正則表達式 | 含義 | | --- | --- | | `.` | 匹配任何單個字符。 | | `?` | 一次匹配或根本不匹配前面的元素。 | | `+` | 與前面的元素匹配一次或多次。 | | `*` | 與前面的元素匹配零次或多次。 | | `^` | 匹配字符串中的起始位置。 | | `$` | 匹配字符串中的結束位置。 | | <code>&#124;</code> | 備用運算符。 | | `[abc]` | 匹配`a`或`b`或`c`。 | | `[a-c]` | 范圍; 匹配`a`或`b`或`c`。 | | `[^abc]` | 否定,匹配除`a`或`b`或`c`之外的所有內容。 | | `\s` | 匹配空白字符。 | | `\w` | 匹配單詞字符; 等同于`[a-zA-Z_0-9]` | ## Kotlin `containsMatchIn`方法 如果正則表達式與整個輸入字符串匹配,則`matches()`方法返回`true`。 `containsMatchIn()`方法指示正則表達式是否可以在指定的輸入中找到至少一個匹配項。 `KotlinRegexSimple.kt` ```kt package com.zetcode fun main(args : Array<String>) { val words = listOf("book", "bookworm", "Bible", "bookish","cookbook", "bookstore", "pocketbook") val pattern = "book".toRegex() println("*********************") println("containsMatchIn function") words.forEach { word -> if (pattern.containsMatchIn(word)) { println("$word matches") } } println("*********************") println("matches function") words.forEach { word -> if (pattern.matches(word)) { println("$word matches") } } } ``` 在示例中,我們使用`matches()`和`containsMatchIn()`方法。 我們有一個單詞表。 模式將使用這兩種方法在每個單詞中尋找一個`"book"`字符串。 ```kt val pattern = "book".toRegex() ``` 使用`toRegex()`方法創建正則表達式模式。 正則表達式由四個普通字符組成。 ```kt words.forEach { word -> if (pattern.containsMatchIn(word)) { println("$word matches") } } ``` 我們遍歷列表,并對每個單詞應用`containsMatchIn()`。 ```kt words.forEach { word -> if (pattern.matches(word)) { println("$word matches") } } ``` 我們再次遍歷該列表,并對每個單詞應用`matches()`。 ```kt ********************* containsMatchIn function book matches bookworm matches bookish matches cookbook matches bookstore matches pocketbook matches ********************* matches function book matches ``` 對于`containsMatchIn()`方法,如果`"book"`單詞在單詞中某處,則模式匹配; 對于`matches()`,輸入字符串必須完全匹配模式。 ## Kotlin `find()方法 `find()`方法返回輸入中正則表達式的第一個匹配項,從指定的起始索引開始。 起始索引默認為 0。 `KotlinRegexFind.kt` ```kt package com.zetcode fun main(args : Array<String>) { val text = "I saw a fox in the wood. The fox had red fur." val pattern = "fox".toRegex() val found = pattern.find(text) val m = found?.value val idx = found?.range println("$m found at indexes: $idx") val found2 = pattern.find(text, 11) val m2 = found2?.value val idx2 = found2?.range println("$m2 found at indexes: $idx2") } ``` 在示例中,我們找到了`"fox"`項匹配項的索引。 ```kt val found = pattern.find(text) val m = found?.value val idx = found?.range ``` 我們找到`"fox"`一詞的第一個匹配項。 我們得到它的值和索引。 ```kt val found2 = pattern.find(text, 11) val m2 = found2?.value val idx2 = found2?.range ``` 在第二種情況下,我們從索引 11 開始搜索,從而找到下一項。 ```kt fox found at indexes: 8..10 fox found at indexes: 29..31 ``` 這是輸出。 ## Kotlin `findAll`方法 `findAll()`方法返回輸入字符串中所有出現的正則表達式的序列。 `KotlinFindAll.kt` ```kt package com.zetcode fun main(args : Array<String>) { val text = "I saw a fox in the wood. The fox had red fur." val pattern = "fox".toRegex() val found = pattern.findAll(text) found.forEach { f -> val m = f.value val idx = f.range println("$m found at indexes: $idx") } } ``` 在示例中,我們使用`findAll()`查找所有出現的'fox'術語。 ## Kotlin `split()`方法 `split()`方法將輸入字符串拆分為正則表達式的匹配項。 `KotlinRegexSplitting.js` ```kt package com.zetcode fun main(args: Array<String>) { val text = "I saw a fox in the wood. The fox had red fur." val pattern = "\\W+".toRegex() val words = pattern.split(text).filter { it.isNotBlank() } println(words) } ``` 在示例中,我們找出`"fox"`項的出現次數。 ```kt val pattern = "\\W+".toRegex() ``` 該模式包含`\W`命名的字符類,代表非單詞字符。 與`+`量詞結合使用時,該模式會查找非單詞字符,例如空格,逗號或點,這些字符通常用于分隔文本中的單詞。 請注意,字符類是兩次轉義的。 ```kt val words = pattern.split(text).filter { it.isNotBlank() } ``` 使用`split()`方法,我們將輸入字符串分成單詞列表。 此外,我們刪除了空白的結尾詞,該詞是由于我們的文本以非單詞字符結尾而創建的。 ```kt [I, saw, a, fox, in, the, wood, The, fox, had, red, fur] ``` 這是輸出。 ## 不區分大小寫的匹配 為了啟用不區分大小寫的搜索,我們將`RegexOption.IGNORE_CASE`傳遞給`toRegex()`方法。 `KotlinRegexCaseInsensitive.kt` ```kt package com.zetcode fun main(args: Array<String>) { val words = listOf("dog", "Dog", "DOG", "Doggy") val pattern = "dog".toRegex(RegexOption.IGNORE_CASE) words.forEach { word -> if (pattern.matches(word)) { println("$word matches") } } } ``` 在示例中,無論大小寫如何,我們都將模式應用于單詞。 ```kt val pattern = "dog".toRegex(RegexOption.IGNORE_CASE) ``` 我們使用`RegexOption.IGNORE_CASE`忽略輸入字符串的大小寫。 ```kt dog matches Dog matches DOG matches ``` 這是輸出。 ## 點元字符 點(。)元字符代表文本中的任何單個字符。 `KotlinRegexDotMeta.kt` ```kt package com.zetcode fun main(args : Array<String>) { val words = listOf("seven", "even", "prevent", "revenge", "maven", "eleven", "amen", "event") val pattern = "..even".toRegex() words.forEach { word -> if (pattern.containsMatchIn(word)) { println("$word matches") } } } ``` 在示例中,列表中有八個單詞。 我們在每個單詞上應用一個包含兩個點元字符的模式。 ```kt prevent matches eleven matches ``` 有兩個與模式匹配的單詞。 ## 問號元字符 問號(?)元字符是與上一個元素零或一次匹配的量詞。 `KotlinRegexQMarkMeta.kt` ```kt package com.zetcode fun main(args : Array<String>) { val words = listOf("seven", "even", "prevent", "revenge", "maven", "eleven", "amen", "event") val pattern = ".?even".toRegex() words.forEach { word -> if (pattern.matches(word)) { println("$word matches") } } } ``` 在示例中,我們在點字符后添加問號。 這意味著在模式中我們可以有一個任意字符,也可以在那里沒有任何字符。 ```kt seven matches even matches ``` 這是輸出。 ## `{n,m}`量詞 `{n,m}`量詞至少匹配前一個表達式的`n`個,最多匹配`m`個。 `KotlinRegexMnQuantifier.kt` ```kt package com.zetcode fun main(args: Array<String>) { val words = listOf("pen", "book", "cool", "pencil", "forest", "car", "list", "rest", "ask", "point", "eyes") val pattern = "\\w{3,4}".toRegex() words.forEach { word -> if (pattern.matches(word)) { println("$word matches") } else { println("$word does not match") } } } ``` 在示例中,我們搜索具有三個或四個字符的單詞。 ```kt val pattern = "\\w{3,4}".toRegex() ``` 在模式中,我們將一個單詞字符重復三到四次。 請注意,數字之間不能有空格。 ```kt pen matches book matches cool matches pencil does not match forest does not match car matches list matches rest matches ask matches point does not match eyes matches ``` 這是輸出。 ## 錨點 錨點匹配給定文本內字符的位置。 當使用^錨時,匹配必須發生在字符串的開頭,而當使用$錨時,匹配必須發生在字符串的結尾。 `KotlinRegexAnchors.kt` ```kt package com.zetcode fun main(args : Array<String>) { val sentences = listOf("I am looking for Jane.", "Jane was walking along the river.", "Kate and Jane are close friends.") val pattern = "^Jane".toRegex() sentences.forEach { sentence -> if (pattern.containsMatchIn(sentence)) { println("$sentence") } } } ``` 在示例中,我們有三個句子。 搜索模式為`^Jane`。 該模式檢查`"Jane"`字符串是否位于文本的開頭。 `Jane\.`將在句子結尾處查找`"Jane"`。 ## 交替 交替運算符| 創建具有多種選擇的正則表達式。 `KotlinRegexAlternations.kt` ```kt package com.zetcode fun main(args: Array<String>) { val words = listOf("Jane", "Thomas", "Robert", "Lucy", "Beky", "John", "Peter", "Andy") val pattern = "Jane|Beky|Robert".toRegex() words.forEach { word -> if (pattern.matches(word)) { println("$word") } } } ``` 列表中有八個名稱。 ```kt val pattern = "Jane|Beky|Robert".toRegex() ``` 此正則表達式查找`Jane`,`"Beky"`或`"`Robert"`字符串。 ## 子模式 子模式是模式中的模式。 子模式使用`()`字符創建。 `KotlinRegexSubpatterns.kt` ```kt package com.zetcode fun main(args: Array<String>) { val words = listOf("book", "bookshelf", "bookworm", "bookcase", "bookish", "bookkeeper", "booklet", "bookmark") val pattern = "book(worm|mark|keeper)?".toRegex() words.forEach { word -> if (pattern.matches(word)) { println("$word matches") } else { println("$word does not match") } } } ``` 該示例創建一個子模式。 ```kt val pattern = "book(worm|mark|keeper)?".toRegex() ``` 正則表達式使用子模式。 它與書呆子,書簽,簿記員和書本單詞匹配。 ```kt book matches bookshelf does not match bookworm matches bookcase does not match bookish does not match bookkeeper matches booklet does not match bookmark matches ``` 這是輸出。 ## 字符類 字符類定義了一組字符,任何字符都可以出現在輸入字符串中以使匹配成功。 `KotlinRegexChClass.kt` ```kt package com.zetcode fun main(args: Array<String>) { val words = listOf("a gray bird", "grey hair", "great look") val pattern = "gr[ea]y".toRegex() words.forEach { word -> if (pattern.containsMatchIn(word)) { println("$word") } } } ``` 在該示例中,我們使用字符類同時包含灰色和灰色單詞。 ```kt val pattern = "gr[ea]y".toRegex() ``` `[ea]`類允許在模式中使用'e'或'a'字符。 ## 命名字符類 有一些預定義的字符類。 `\s`與空白字符`[\t\n\t\f\v]`匹配,`\d`與數字`[0-9]`匹配,`\w`與單詞字符`[a-zA-Z0-9_]`匹配。 `KotlinRegexNamedClass.kt` ```kt package com.zetcode fun main(args: Array<String>) { val text = "We met in 2013\. She must be now about 27 years old." val pattern = "\\d+".toRegex() val found = pattern.findAll(text) found.forEach { f -> val m = f.value println("$m") } } ``` 在示例中,我們在文本中搜索數字。 ```kt val pattern = "\\d+".toRegex() ``` `\d+`模式在文本中查找任意數量的數字集。 ```kt val found = pattern.findAll(text) ``` 用`findAll()`查找所有匹配項。 ```kt 2013 27 ``` 這是輸出。 ## 捕獲組 捕獲組是一種將多個字符視為一個單元的方法。 通過將字符放置在一組圓括號內來創建它們。 例如,`(book)`是包含`'b', 'o', 'o', 'k'`字符的單個組。 捕獲組技術使我們能夠找出字符串中與正則表達式模式匹配的那些部分。 `KotlinRegexCapturingGroups.kt` ```kt package com.zetcode fun main(args: Array<String>) { val content = """<p>The <code>Pattern</code> is a compiled representation of a regular expression.</p>""" val pattern = "(<\\/?[a-z]*>)".toRegex() val found = pattern.findAll(content) found.forEach { f -> val m = f.value println("$m") } } ``` 該代碼示例通過捕獲一組字符來打印提供的字符串中的所有 HTML 標簽。 ```kt val found = pattern.findAll(content) ``` 為了找到所有標簽,我們使用`findAll()`方法。 ```kt <p> <code> </code> </p> ``` 我們找到了四個 HTML 標簽。 ## Kotlin 正則表達式電子郵件示例 在以下示例中,我們創建一個用于檢查電子郵件地址的正則表達式模式。 `KotlinRegexEmails.kt` ```kt package com.zetcode fun main(args: Array<String>) { val emails = listOf("luke@gmail.com", "andy@yahoocom", "34234sdfa#2345", "f344@gmail.com", "dandy!@yahoo.com") val pattern = "[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\\.[a-zA-Z.]{2,18}".toRegex() emails.forEach { email -> if (pattern.matches(email)) { println("$email matches") } else { println("$email does not match") } } } ``` 本示例提供了一種可能的解決方案。 ```kt val pattern = "[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\\.[a-zA-Z.]{2,18}".toRegex() ``` 電子郵件分為五個部分。 第一部分是本地部分。 通常,它是公司名稱,個人名稱或昵稱。 `[a-zA-Z0-9._-]+`列出了我們可以在本地部分使用的所有可能的字符。 它們可以使用一次或多次。 第二部分由文字`@`字符組成。 第三部分是領域部分。 通常是電子郵件提供商的域名,例如 yahoo 或 gmail。 `[a-zA-Z0-9-]+`是一個字符類,提供可在域名中使用的所有字符。 `+`量詞允許使用這些字符中的一個或多個。 第四部分是點字符。 它前面是雙轉義字符(\\)以獲取文字點。 最后一部分是頂級域名:`[a-zA-Z.]{2,18}`。 頂級域可以包含 2 到 18 個字符,例如`sk, net, info, travel, cleaning, travelinsurance`最大長度可以為 63 個字符,但是今天大多數域都少于 18 個字符。 還有一個點字符。 這是因為某些頂級域包含兩個部分: 例如`co.uk`。 ```kt luke@gmail.com matches andy@yahoocom does not match 34234sdfa#2345 does not match f344@gmail.com matches dandy!@yahoo.com does not match ``` 這是輸出。 在本章中,我們介紹了 Kotlin 中的正則表達式。 您可能也對以下相關教程感興趣: [Kotlin 范圍教程](/kotlin/ranges/)和 [Kotlin 設置教程](/kotlin/sets/)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看