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

Closed
xopoww opened this issue Jun 26, 2020 · 3 comments
Closed

regexp.QuoteMeta does not escape "-" #39867

xopoww opened this issue Jun 26, 2020 · 3 comments
Labels
FrozenDueToAge WaitingForInfo Issue is not actionable because of missing required information, which needs to be provided.

Comments

@xopoww
Copy link

xopoww commented Jun 26, 2020

$ go version go1.14.4 windows/amd64

Sample code recreating an issue (playground):

package main

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

func main() {
	fmt.Println(re1.ReplaceAllString("123456", "☺"))
	fmt.Println(re2.ReplaceAllString("123456", "☺"))
}
Output:
☺☺☺☺☺☺
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 "=".

@mvdan
Copy link
Member

mvdan commented Jun 26, 2020

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

@mvdan mvdan added the WaitingForInfo Issue is not actionable because of missing required information, which needs to be provided. label Jun 26, 2020
@junyer
Copy link
Contributor

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.

@gopherbot
Copy link

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.)

@golang golang locked and limited conversation to collaborators Aug 6, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
FrozenDueToAge WaitingForInfo Issue is not actionable because of missing required information, which needs to be provided.
Projects
None yet
Development

No branches or pull requests

4 participants