Skip to content
Advertisement

Extract username from url with regex

I am extracting usernames from urls using ^(?:https?://)?(?:www.)?(?:website.com)?/?([^/s]+). This method will return “username?lang=en”. How can i remove the “?lang=en” from the end ?

Advertisement

Answer

You can use

^(?:https?://)?(?:www.)?(?:website.com)?/?([^/s?#]+)

See the regex demo. Details:

  • ^ – start of string
  • (?:https?://)? – an optional occurrence of http:// or https://
  • (?:www.)? – an optional occurrence of www. (note that the literal dot must be escaped)
  • (?:website.com)? – an optional occurrence of website.com
  • /? – an optional / char
  • ([^/s?#]+) – Group 1: one or more chars other than /, whitespace, ? and # chars.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement