Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

regexp.QuoteMeta does not escape "-" #39867

xopoww opened this issue Jun 26, 2020 · 3 comments

regexp.QuoteMeta does not escape "-" #39867

xopoww opened this issue Jun 26, 2020 · 3 comments


Copy link

@xopoww xopoww commented Jun 26, 2020

$ go version go1.14.4 windows/amd64

Sample code recreating an issue (playground):

package main

import (
var (
	re1 = regexp.MustCompile("["+regexp.QuoteMeta("+-=|")+"]")
	re2 = regexp.MustCompile("["+regexp.QuoteMeta("-+=|")+"]")

func main() {
	fmt.Println(re1.ReplaceAllString("123456", "☺"))
	fmt.Println(re2.ReplaceAllString("123456", "☺"))

regexp.QuoteMeta function does not escape "-" character. I don't know if this is intentional design, but in some situations this may lead to an unexpeted behavior, e.g. instead of group of 4 symbols I got a group of "|" and a range betweeen "+ and "=".

Copy link

@mvdan mvdan commented Jun 26, 2020

You should use QuoteMeta on the entire expression, and that will quote your [ character.

Copy link

@junyer junyer commented Jun 28, 2020

regexp.QuoteMeta("+-=|") returns a pattern string that matches the input string "+-=|". You can't put it inside a character class because the rules inside character classes are completely different. Instead, try splitting "+-=|" into single-character strings, running regexp.QuoteMeta on each string and joining the results with |. (Enclose the whole thing in (?: and ) if necessary.) The Go regexp package should optimise that down to a character class.

Copy link

@gopherbot gopherbot commented Aug 6, 2020

Timed out in state WaitingForInfo. Closing.

(I am just a bot, though. Please speak up if this is a mistake or you have the requested information.)

@gopherbot gopherbot closed this Aug 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants
You can’t perform that action at this time.