Golang多行正则表达式不起作用

为什么以下多行正则表达式不起作用,我希望匹配标签内的子字符串。其他简单的多行匹配工作正常。


func main() {

    r := regexp.MustCompile(`(?m)<think>(.*)</think>`)

    const s = `That is 

    <think>

    FOOBAR

    </think>`

    fmt.Printf("%#v\n", r.FindStringSubmatch(s))

}

https://play.golang.org/p/8C6u_0ca8w


临摹微笑
浏览 349回答 2
2回答

互换的青春

默认情况下, ”。”&nbsp;不匹配换行符。如果你给“s”标志,它确实如此。我认为你不需要“m”。请注意,如果<think>...</think>您的字符串中有多个,则正则表达式将匹配 first<think>和 last之间的所有内容</think>。使用.*?将导致它只匹配第一个的内容。

鸿蒙传说

不要使用正则表达式来解析 XML,而是使用encoding/xml。在正则表达式中无法处理的极端情况示例:<think><elem attrib="I'm pondering about </think> tag now"></elem></think>我将使用STARTandSTOP作为标记,只是为了与任何 XML 内容分离。完整的示例(包括 LF 和 CRLF 行结尾,以防万一)与Go Playground的链接:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "regexp")func main() {&nbsp; &nbsp; r := regexp.MustCompile(`(?s)START(.*?)STOP`)&nbsp; &nbsp; const s = "That is \nSTART\nFOOBAR\r\n\r\nSTOP\n"&nbsp; &nbsp; fmt.Printf("%#v\n", r.FindStringSubmatch(s))}返回:[]string{"START\nFOOBAR\r\n\r\nSTOP", "\nFOOBAR\r\n\r\n"}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go