首页 > 后端开发 > 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学习者快速成长!