Skip to content

regexp: LiteralPrefix returns surprising result for ^ anchored strings #33506

Open
@eliben

Description

@eliben

What version of Go are you using (go version)?

$ go version
go version go1.12.5 linux/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GOARCH="amd64"
GOBIN=""
GOCACHE="/usr/local/google/home/eliben/.cache/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/usr/local/google/home/eliben/go"
GOPROXY="https://proxy.golang.org"
GORACE=""
GOROOT="/usr/lib/google-golang"
GOTMPDIR=""
GOTOOLDIR="/usr/lib/google-golang/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build346731385=/tmp/go-build -gno-record-gcc-switches"

What did you do?

package main

import (
	"fmt"
	"regexp"
)

func main() {
	for _, p := range []string{"foo", "^foo"} {
		prefix, _ := regexp.MustCompile(p).LiteralPrefix()
		fmt.Printf("prefix = '%v'\n", prefix)
	}
}

What did you expect to see?

The documentation for LiteralPrefix says:

LiteralPrefix returns a literal string that must begin any match of the regular expression re. It returns the boolean true if the literal string comprises the entire regular expression.

So I expected to see "foo" in both cases, since every any match of the regular expression ^foo begins with the literal "foo".

prefix = 'foo'
prefix = 'foo'

What did you see instead?

prefix = 'foo'
prefix = ''

In #21463 (comment), @rsc says:

"It looks like the literal prefix matcher doesn't kick in for anchored patterns, and we should fix that.

Also, see discussion in #30425

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions