首頁  >  文章  >  後端開發  >  為什麼即使 `s` 設定為 True,Go 的正規表示式 `.` 也不符合換行符?

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

Patricia Arquette
Patricia Arquette原創
2024-10-28 01:52:02659瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn