158人参与 • 2025-02-14 • Golang
text := `first line second line third line` // 看似正确但可能失效的正则 pattern := "first.*third" matched, _ := regexp.match(pattern, []byte(text)) fmt.println(matched) // false
.不匹配换行符\n 和 \r\n 的平台差异// 启用单行模式(让 . 匹配换行符) pattern := `(?s)first.*third` matched, _ := regexp.match(pattern, []byte(text)) fmt.println(matched) // true
// 匹配任意字符(包括换行) pattern := `first[\s\s]*third` matched, _ := regexp.match(pattern, []byte(text)) fmt.println(matched) // true
// 处理多行文本时的行首行尾 pattern := `(?m)^line\d$` matches := regexp.mustcompile(pattern).findallstring(text, -1)
func extractcomments(code string) []string {
pattern := `(?s)/\*.*?\*/`
re := regexp.mustcompile(pattern)
return re.findallstring(code, -1)
}
// 测试
code := `
/* 这是一个
多行注释 */
func main() {
/* 另一个注释 */
}
`
comments := extractcomments(code)
func parselogentry(log string) []logentry {
pattern := `(?m)^(\d{4}-\d{2}-\d{2})\s+(.*)$`
re := regexp.mustcompile(pattern)
matches := re.findallstringsubmatch(log, -1)
var entries []logentry
for _, match := range matches {
entries = append(entries, logentry{
date: match[1],
content: match[2],
})
}
return entries
}
// 好的做法
var commentregex = regexp.mustcompile(`(?s)/\*.*?\*/`)
func process(input string) {
matches := commentregex.findallstring(input, -1)
// ...
}
// 避免回溯过多 pattern := `(?s)/\*.*?\*/` // 使用非贪婪模式 // 而不是 pattern := `(?s)/\*.*\*/` // 贪婪模式可能导致性能问题
// 处理跨平台换行符 pattern := `(?s)line1[\r\n]+line2` // 或者 pattern := `(?s)line1\r+line2`
// 启用 unicode 支持 pattern := `(?s)(?u)first.*third`
// 非贪婪匹配 pattern := `(?s)".*?"` // 贪婪匹配 pattern := `(?s)".*"`
(?s): 单行模式(?m): 多行模式(?i): 忽略大小写(?u): unicode 支持\r 匹配通用换行调试技巧
// 打印正则匹配过程
debug := regexp.mustcompile(pattern)
fmt.printf("pattern: %q\n", debug.string())
fmt.printf("groups: %d\n", debug.numsubexp())
处理 go 语言中的正则表达式换行符问题,关键在于:
(?s) 标志的作用以上就是go语言利用正则表达式处理多行文本的详细内容,更多关于go处理多行文本的资料请关注代码网其它相关文章!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论