4

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
himmip
  • 1,360
  • 2
  • 12
  • 24
  • 1
    Who is submitting a close-vote with the reason as "Not reproducible or was caused by a typo"? What exactly in the example code provided in the question is not reproducible? The specified behavior is 100% reproducible. Here is the Go playground for it: https://play.golang.org/p/muUxpBOmOQV. It produces the output `false` exactly as mentioned in this question. Really, who is it that is going around close-voting most Go questions with this fake reason? Why are they doing this? – Lone Learner Aug 21 '20 at 11:38
  • 1
    @LoneLearner: Totally agree with your point. From the many tags I follow, only here do I notice, more than decent questions with a proper [MCVE](https://stackoverflow.com/help/minimal-reproducible-example) getting downvoted and voted to close – Inian Aug 21 '20 at 11:46

1 Answers1

4

There are two major issues:

  • You are using a regex literal as a string regex pattern. It means, you need to remove the first and last / and "move" m flag to the pattern by converting it into a (?m) inline modifier
  • You are only match the first occurrence with MatchString (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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563