2
src.match(/^(https?\:\/\/.*)\//)

I know regular expressions but the syntax is not familiar to me. Can somebody explain to me what it's matching?

5 Answers 5

7

Matches anything that starts with http:// or https:// followed by any number of any character (.*), followed by another / slash.

The / slashes need to be escaped. I don't know why the colon is escaped too.

Sign up to request clarification or add additional context in comments.

1 Comment

In addition to this, the .* is done greedily, so <a href="http://mysite.com/mypage.php">go to mypage</a> will result with http://mysite.com/mypage.php">go to mypage< in match[1]. I'm not saying this regex is flawed in that fashion, you just need to be aware of it when using.
4
  • ^ start of string
  • ( start of a capture group
    • http the characters "http"
    • s? zero or one of the character "s"
    • \: a colon character (escaped, though not necessary)
    • \/\/ two forward slash characters (escaped so that it doesn't close the regex literal)
    • .* zero more more of any character, except a line break
  • ) end of the capture group
  • \/ a forward slash chararacter (escaped so that it doesn't close the regex literal)

The starting and ending / characters simply denote regular expression literal notation.

Comments

1

A string that starts with "http"/"https", followed by ://, followed by any number of characters (greedily), and then by a trailing /.

The match itself will be exactly what's searched, minus the last /.

Comments

1

It's a pretty ordinary regex:

^ At the start of the string

( Start a capture

http Match "http" literally

s? Match an optional "s"

\: Match a literal colon

\/ Match a literal slash

\/ Match a literal slash

.* Then as many characters as possible

) End the capture

\/ Ending at a literal slash

The regex has the effect of capturing the protocol, host, and path from a URL and excluding any file at the end. For instance in the case of https://www.host.com/path/to/my/file.cgi, https://www.host.com/path/to/my would be captured.

Comments

1

These are some examples of what would that regex match:

https://www.aaa.bb/
http://www.aaa.bb/
http://some.server/
http://aa/
http:///
https:///
http:////////////
https:////////////

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.