Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression with beginning of line

Tags:

regex

go

I'd like to use a regular expression which matches the beginning of a line in a text. For some reason, ^ does not work, see this failing test:

func TestNewLine(t *testing.T) {
    re := regexp.MustCompile("^bar")
    match := re.FindString("foo\nbar\nbaz")
    assert.Equal(t, "bar", match)
}

What do I miss?

like image 809
zuraff Avatar asked Sep 06 '25 20:09

zuraff


1 Answers

You have to enable multi line mode flag for regex evaluation. Try this:

func TestNewLine(t *testing.T) {
    re := regexp.MustCompile("(?m)^(bar)")
    match := re.FindString("foo\nbar\nbaz")
    assert.Equal(t, "bar", match)
}
like image 176
Greg Avatar answered Sep 09 '25 20:09

Greg