由于golang中不支持'm'修饰符,我们可以使用其他方式来实现匹配不以特定字符串开头的多行文本。
一种解决方法是使用反向引用,如下所示:
import (
"regexp"
)
func main() {
str := "some text\nmore text\n
even more text\n
last text"
re := regexp.MustCompile(`(?:\A|[^\r\n])(?:(?!
\s*$)[\s\S])*`)
matches := re.FindAllString(str, -1)
for _, match := range matches {
if !regexp.MustCompile(`^\s*`).MatchString(match) {
fmt.Println(match)
}
}
}
在上面的示例中,我们使用正则表达式(?:\A|[^\r\n])(?:(?!
(?:\A|[^\r\n])
匹配字符串的开头,或者匹配一个非换行符的字符。(?:(?!\s*$)[\s\S])*
匹配多行文本。这个正则表达式使用了一个负向前瞻,即(?!...)
来排除以
开头的行。[\s\S]
表示匹配任意字符(包括换行符),*
表示匹配零个或多个这样的组合。最后,我们使用!regexp.MustCompile(
^\s*
).MatchString(match)
来判断每个匹配项是否以开头,如果不是,则打印匹配项。
运行上面的代码,可以得到输出:
some text
even more text
last text
这些文本不以开