-1

I m trying to validate the image url using golang code but there is error in regular expression I'm showing my regular expression in this question:-

 var validation = regexp.MustCompile("(http(s?):)|([/|.|\w|\s])*\.(?:jpg|gif|png)")

Error:-

unknown escape sequence (and 2 more errors)

play link

stack
  • 31
  • 1
  • 7
  • I'd suggest using backtics when defining regex so that you won't have to escape "\" – ssemilla Nov 17 '18 at 09:51
  • @ssemilla can you tell me what corrections – stack Nov 17 '18 at 09:52
  • Replace " with `. I didn't actually review your regex but people usually make mistakes when they mean "\\" rather than "\". Using backtics instead makes it very clear what we mean since nothing is escaped. – ssemilla Nov 17 '18 at 09:52
  • @ssemilla By using ` instead of " it runs but not working properly it prints nothing – stack Nov 17 '18 at 09:55
  • Why are you using `!validation.MatchString()` instead of just `validation.MatchString()`? – ssemilla Nov 17 '18 at 09:58
  • @ssemilla Can you tell me from start how i will write a proper regular expression in golang? – stack Nov 17 '18 at 10:08

1 Answers1

0

\. is an invalid escape sequence. I would suggest you use backticks when defining regular expressions. e.g.

regexp.MustCompile(`^https?://.*\.(jpg|gif|png)$`) // this will just check if the url ends with jpg,gif,png

If you are not using the capture groups, this is a simpler approach. However when parsing or validating URLs, use url.Parse() which provides better validation.

ssemilla
  • 3,900
  • 12
  • 28
  • This might be a more proper regex for the URL: `^https?://(?:[a-z0-9\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$` which was taken from here: https://stackoverflow.com/questions/169625/regex-to-check-if-valid-url-that-ends-in-jpg-png-or-gif – ssemilla Nov 17 '18 at 10:43
  • if I used your code given regexp it was also correct?' – stack Nov 17 '18 at 11:44
  • It won't validate invalid URL characters. I suggest you use `^https?://(?:[a-z0-9\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$` if you really need a regex. – ssemilla Nov 17 '18 at 11:46