首頁 > 後端開發 > Golang > 主體

為什麼即使 `s` 設定為 True,Go 的正規表示式 `.` 也不符合換行符?

Patricia Arquette
發布: 2024-10-28 01:52:02
原創
667 人瀏覽過

Why Doesn't Go's Regex `.` Match Newlines Even When `s` is Set to True?

Go 正則表達式與換行符:微妙的區別

儘管Go 的re2 語法聲明聲明任何字符(.) 匹配任何字符,當's' 設定為true 時包括換行符,一個簡單的程式表示情況並非如此。

程式輸出

s set to true
not matched
s set to false
matched
登入後複製
登入後複製

解釋

與許多其他正規表示式引擎一樣,點字(.)僅匹配常規字元。若要在符合中包含換行符,必須將「dot all」標誌 (?s) 新增至正規表示式。

範例

<code class="go">import (
    "fmt"
    "regexp"
)

func main() {
    const text = "This is a test.\nAnd this is another line."

    // Without the "dot all" flag, newline is not matched.
    r1 := regexp.MustCompile(".+")
    fmt.Printf("s set to true\n")
    if !r1.MatchString(text) {
        fmt.Println("not matched")
    }

    // With the "dot all" flag, newline is matched.
    r2 := regexp.MustCompile("(?s).+")
    fmt.Printf("s set to false\n")
    if r2.MatchString(text) {
        fmt.Println("matched")
    }
}</code>
登入後複製

輸出

s set to true
not matched
s set to false
matched
登入後複製
登入後複製

因此,要使用Go 正規表示式運算式換行符必須在正規表示式模式中包含「dot all」標誌(?s)。

以上是為什麼即使 `s` 設定為 True,Go 的正規表示式 `.` 也不符合換行符?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!