golang regexp.MatchString handle url match

Viewed 1853

I wanna check if a url string match keyword, for example, keyword is google.com, if url string is google.com or https://google.com, then return true, if url is google.com/search or something like that, return true, if url is google.com.id, then return false as it's a different url, I tried one as below but it doesn't work, how to write regular expression? thank u

regexp.MatchString(`^(?:https?://)?([-a-z0-9]+)(?:\.`+keyword+`)*$`, urlstr)

btw, as far as I understood, regular expression will cause some performance issue, anyone can provide other solutions to handle it?

1 Answers

You can use

regexp.MatchString(`^(?:https?://)?(?:[^/.\s]+\.)*` + regexp.QuoteMeta(keyword) + `(?:/[^/\s]+)*/?$`)

See the regex demo.

Details:

  • ^ - start of string
  • (?:https?://)? - an optional http:// or https://
  • (?:[^/\s]+\.)* - zero or more repetitions of
    • [^/.\s]+ - one or more chars other than /, . and whitespace
    • \. - a dot
  • google\.com - an escaped keyword
  • (?:/[^/\s]+)* - zero or more repetitions of a / and then one or more chars other than / and whitespace chars
  • /? - an optional /
  • $ - end of string

Note you need to use regexp.QuoteMeta to escape any special chars in the keyword, like a . that matches any char but line break chars by default.

Related