I have a regex that is not matching in Go.
However in a regex playground it's matching fine: https://regex101.com/r/VNDXcQ/2.
It's matching JS comments.
Here is the code:
comment := "// fallback response. For more information contact support"
re := regexp.MustCompile(`/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm`)
matches := re.MatchString(comment)
fmt.Println(matches) // false
Why could that be?
There are two major issues:
/
and "move" m
flag to the pattern by converting it into a (?m)
inline modifierMatchString
(since flags cannot be passed along with the regex pattern and g
flag "is not supported"). You need to use FindAllString
to get all matches.You can fix that with
re := regexp.MustCompile(`(?m)/\*[\s\S]*?\*/|([^\\:]|^)//.*`)
matches := re.FindAllString(comment, -1)
Note /
is not a special character and thus needs no escaping.
See Go playground.