<p>Given the URL (single line):<br>
<a href="http://test.example.com/dir/subdir/file.html" rel="noreferrer">http://test.example.com/dir/subdir/file.html</a></p>

<p>How can I extract the following parts using regular expressions:</p>

<ol>
<li>The Subdomain (test)</li>
<li>The Domain (example.com)</li>
<li>The path without the file (/dir/subdir/)</li>
<li>The file (file.html)</li>
<li>The path with the file (/dir/subdir/file.html)</li>
<li>The URL without the path (<a href="http://test.example.com" rel="noreferrer">http://test.example.com</a>)</li>
<li>(add any other that you think would be useful)</li>
</ol>

<p>The regex should work correctly even if I enter the following URL:  </p>

<pre><code>http://example.example.com/example/example/example.html
</code></pre>

[{'answer_id': 27755, 'author': 'hometoast', 'author_id': 2009, 'author_profile': 'https://Stackoverflow.com/users/2009', 'pm_score': 8, 'selected': True, 'text': '<blockquote>\n  <p>A single regex to parse and breakup a\n  full URL including query parameters\n  and anchors e.g.</p>\n  \n  <p><a href="https://www.google.com/dir/1/2/search.html?arg=0-a&amp;arg1=1-b&amp;arg3-c#hash" rel="noreferrer">https://www.google.com/dir/1/2/search.html?arg=0-a&amp;arg1=1-b&amp;arg3-c#hash</a> </p>\n  \n  <p><code>^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(.*)?(#[\\w\\-]+)?$</code></p>\n  \n  <p>RexEx positions:</p>\n  \n  <p>url: RegExp[\'$&amp;\'], </p>\n  \n  <p>protocol:RegExp.$2,</p>\n  \n  <p>host:RegExp.$3, </p>\n  \n  <p>path:RegExp.$4,</p>\n  \n  <p>file:RegExp.$6, </p>\n  \n  <p>query:RegExp.$7,</p>\n  \n  <p>hash:RegExp.$8</p>\n</blockquote>\n\n<p>you could then further parse the host (\'.\' delimited) quite easily.</p>\n\n<p>What <strong>I</strong> would do is use something like this:</p>\n\n<pre><code>/*\n    ^(.*:)//([A-Za-z0-9\\-\\.]+)(:[0-9]+)?(.*)$\n*/\nproto $1\nhost $2\nport $3\nthe-rest $4\n</code></pre>\n\n<p>the further parse \'the rest\' to be as specific as possible. Doing it in one regex is, well, a bit crazy.</p>\n'}, {'answer_id': 27759, 'author': 'Mark Ingram', 'author_id': 986, 'author_profile': 'https://Stackoverflow.com/users/986', 'pm_score': 3, 'selected': False, 'text': '<p>Try the following:</p>\n<pre><code>^((ht|f)tp(s?)\\:\\/\\/|~/|/)?([\\w]+:\\w+@)?([a-zA-Z]{1}([\\w\\-]+\\.)+([\\w]{2,5}))(:[\\d]{1,5})?((/?\\w+/)+|/?)(\\w+\\.[\\w]{3,4})?((\\?\\w+=\\w+)?(&amp;\\w+=\\w+)*)?\n</code></pre>\n<p>It supports HTTP / FTP, subdomains, folders, files etc.</p>\n<p>I found it from a quick google search:</p>\n<p><a href="https://web.archive.org/web/20210126191109/http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx" rel="nofollow noreferrer">Link</a></p>\n'}, {'answer_id': 27768, 'author': 'tgmdbm', 'author_id': 1851, 'author_profile': 'https://Stackoverflow.com/users/1851', 'pm_score': 3, 'selected': False, 'text': '<p>subdomain and domain are difficult because the subdomain can have several parts, as can the top level domain, <a href="http://sub1.sub2.domain.co.uk/" rel="noreferrer">http://sub1.sub2.domain.co.uk/</a></p>\n\n<pre><code> the path without the file : http://[^/]+/((?:[^/]+/)*(?:[^/]+$)?)  \n the file : http://[^/]+/(?:[^/]+/)*((?:[^/.]+\\.)+[^/.]+)$  \n the path with the file : http://[^/]+/(.*)  \n the URL without the path : (http://[^/]+/)  \n</code></pre>\n\n<p>(Markdown isn\'t very friendly to regexes)</p>\n'}, {'answer_id': 27775, 'author': 'pek', 'author_id': 2644, 'author_profile': 'https://Stackoverflow.com/users/2644', 'pm_score': 0, 'selected': False, 'text': '<p>Using <a href="http://www.fileformat.info/tool/regex.htm" rel="nofollow noreferrer">http://www.fileformat.info/tool/regex.htm</a> hometoast\'s regex works great.</p>\n\n<p>But here is the deal, I want to use different regex patterns in different situations in my program.</p>\n\n<p>For example, I have this URL, and I have an enumeration that lists all supported URLs in my program. Each object in the enumeration has a method getRegexPattern that returns the regex pattern which will then be used to compare with a URL. If the particular regex pattern returns true, then I know that this URL is supported by my program. So, each enumeration has it\'s own regex depending on where it should look inside the URL.</p>\n\n<p>Hometoast\'s suggestion is great, but in my case, I think it wouldn\'t help (unless I copy paste the same regex in all enumerations).</p>\n\n<p>That is why I wanted the answer to give the regex for each situation separately. Although +1 for hometoast. ;)</p>\n'}, {'answer_id': 27785, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 0, 'selected': False, 'text': "<p>I know you're claiming language-agnostic on this, but can you tell us what you're using just so we know what regex capabilities you have?</p>\n\n<p>If you have the capabilities for non-capturing matches, you can modify hometoast's expression so that subexpressions that you aren't interested in capturing are set up like this:</p>\n\n<p><code>(?:SOMESTUFF)</code></p>\n\n<p>You'd still have to copy and paste (and slightly modify) the Regex into multiple places, but this makes sense--you're not just checking to see if the subexpression exists, but rather if it exists <em>as part of a URL</em>. Using the non-capturing modifier for subexpressions can give you what you need and nothing more, which, if I'm reading you correctly, is what you want.</p>\n\n<p>Just as a small, small note, hometoast's expression doesn't need to put brackets around the 's' for 'https', since he only has one character in there. Quantifiers quantify the one character (or character class or subexpression) directly preceding them. So:</p>\n\n<p><code>https?</code></p>\n\n<p>would match 'http' or 'https' just fine.</p>\n"}, {'answer_id': 27821, 'author': 'Chris Bartow', 'author_id': 497, 'author_profile': 'https://Stackoverflow.com/users/497', 'pm_score': 1, 'selected': False, 'text': '<p>Java offers a URL class that will do this.  <a href="http://java.sun.com/docs/books/tutorial/networking/urls/urlInfo.html" rel="nofollow noreferrer">Query URL Objects.</a></p>\n\n<p>On a side note, PHP offers <a href="http://www.php.net/parse_url" rel="nofollow noreferrer">parse_url()</a>.</p>\n'}, {'answer_id': 309360, 'author': 'mingfai', 'author_id': 39701, 'author_profile': 'https://Stackoverflow.com/users/39701', 'pm_score': 5, 'selected': False, 'text': "<p>I found the highest voted answer (hometoast's answer) doesn't work perfectly for me. Two problems:</p>\n\n<ol>\n<li>It can not handle port number.</li>\n<li>The hash part is broken.</li>\n</ol>\n\n<p>The following is a modified version:</p>\n\n<pre><code>^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:([^\\/]*))?((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(\\?([^#]*))?(#(.*))?$\n</code></pre>\n\n<p>Position of parts are as follows:</p>\n\n<pre><code>int SCHEMA = 2, DOMAIN = 3, PORT = 5, PATH = 6, FILE = 8, QUERYSTRING = 9, HASH = 12\n</code></pre>\n\n<p>Edit posted by anon user:</p>\n\n<pre><code>function getFileName(path) {\n    return path.match(/^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:([^\\/]*))?((\\/[\\w\\/-]+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(\\?([^#]*))?(#(.*))?$/i)[8];\n}\n</code></pre>\n"}, {'answer_id': 441881, 'author': 'strager', 'author_id': 39992, 'author_profile': 'https://Stackoverflow.com/users/39992', 'pm_score': 2, 'selected': False, 'text': '<pre><code>/^((?P&lt;scheme&gt;https?|ftp):\\/)?\\/?((?P&lt;username&gt;.*?)(:(?P&lt;password&gt;.*?)|)@)?(?P&lt;hostname&gt;[^:\\/\\s]+)(?P&lt;port&gt;:([^\\/]*))?(?P&lt;path&gt;(\\/\\w+)*\\/)(?P&lt;filename&gt;[-\\w.]+[^#?\\s]*)?(?P&lt;query&gt;\\?([^#]*))?(?P&lt;fragment&gt;#(.*))?$/\n</code></pre>\n\n<p>From my answer on a <a href="https://stackoverflow.com/questions/441739/regex-for-url-validation-with-parts-capturing#441781">similar question</a>.  Works better than some of the others mentioned because they had some bugs (such as not supporting username/password, not supporting single-character filenames, fragment identifiers being broken).</p>\n'}, {'answer_id': 1140642, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>regexp to get the URL path without the file.</p>\n\n<p>url = \'<a href="http://domain/dir1/dir2/somefile" rel="nofollow noreferrer">http://domain/dir1/dir2/somefile</a>\'\nurl.scan(/^(http://[^/]+)((?:/[^/]+)+(?=/))?/?(?:[^/]+)?$/i).to_s</p>\n\n<p>It can be useful for adding a relative path to this url.</p>\n'}, {'answer_id': 1541830, 'author': 'CallMeLaNN', 'author_id': 186334, 'author_profile': 'https://Stackoverflow.com/users/186334', 'pm_score': 2, 'selected': False, 'text': '<p>You can get all the http/https, host, port, path as well as query by using Uri object in .NET.\njust the difficult task is to break the host into sub domain, domain name and TLD.</p>\n\n<p>There is no standard to do so and can\'t be simply use string parsing or RegEx to produce the correct result. At first, I am using RegEx function but not all URL can be parse the subdomain correctly. The practice way is to use a list of TLDs. After a TLD for a URL is defined the left part is domain and the remaining is sub domain.</p>\n\n<p>However the list need to maintain it since new TLDs is possible. The current moment I know is publicsuffix.org maintain the latest list and you can use domainname-parser tools from google code to parse the public suffix list and get the sub domain, domain and TLD easily by using DomainName object: domainName.SubDomain, domainName.Domain and domainName.TLD.</p>\n\n<p>This answers also helpfull:\n<a href="https://stackoverflow.com/questions/288810/get-the-subdomain-from-a-url">Get the subdomain from a URL</a></p>\n\n<p>CaLLMeLaNN</p>\n'}, {'answer_id': 1821918, 'author': 'Jason', 'author_id': 206908, 'author_profile': 'https://Stackoverflow.com/users/206908', 'pm_score': 1, 'selected': False, 'text': '<p>I would recommend not using regex.  An API call like <em>WinHttpCrackUrl()</em> is less error prone.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/aa384092%28VS.85%29.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa384092%28VS.85%29.aspx</a></p>\n'}, {'answer_id': 3724500, 'author': 'Shelby Moore', 'author_id': 449214, 'author_profile': 'https://Stackoverflow.com/users/449214', 'pm_score': 3, 'selected': False, 'text': "<p>This improved version should work as reliably as a parser.</p>\n\n<pre><code>   // Applies to URI, not just URL or URN:\n   //    http://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Relationship_to_URL_and_URN\n   //\n   // http://labs.apache.org/webarch/uri/rfc/rfc3986.html#regexp\n   //\n   // (?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?\n   //\n   // http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax\n   //\n   // $@ matches the entire uri\n   // $1 matches scheme (ftp, http, mailto, mshelp, ymsgr, etc)\n   // $2 matches authority (host, user:pwd@host, etc)\n   // $3 matches path\n   // $4 matches query (http GET REST api, etc)\n   // $5 matches fragment (html anchor, etc)\n   //\n   // Match specific schemes, non-optional authority, disallow white-space so can delimit in text, and allow 'www.' w/o scheme\n   // Note the schemes must match ^[^\\s|:/?#]+(?:\\|[^\\s|:/?#]+)*$\n   //\n   // (?:()(www\\.[^\\s/?#]+\\.[^\\s/?#]+)|(schemes)://([^\\s/?#]*))([^\\s?#]*)(?:\\?([^\\s#]*))?(#(\\S*))?\n   //\n   // Validate the authority with an orthogonal RegExp, so the RegExp above won’t fail to match any valid urls.\n   function uriRegExp( flags, schemes/* = null*/, noSubMatches/* = false*/ )\n   {\n      if( !schemes )\n         schemes = '[^\\\\s:\\/?#]+'\n      else if( !RegExp( /^[^\\s|:\\/?#]+(?:\\|[^\\s|:\\/?#]+)*$/ ).test( schemes ) )\n         throw TypeError( 'expected URI schemes' )\n      return noSubMatches ? new RegExp( '(?:www\\\\.[^\\\\s/?#]+\\\\.[^\\\\s/?#]+|' + schemes + '://[^\\\\s/?#]*)[^\\\\s?#]*(?:\\\\?[^\\\\s#]*)?(?:#\\\\S*)?', flags ) :\n         new RegExp( '(?:()(www\\\\.[^\\\\s/?#]+\\\\.[^\\\\s/?#]+)|(' + schemes + ')://([^\\\\s/?#]*))([^\\\\s?#]*)(?:\\\\?([^\\\\s#]*))?(?:#(\\\\S*))?', flags )\n   }\n\n   // http://en.wikipedia.org/wiki/URI_scheme#Official_IANA-registered_schemes\n   function uriSchemesRegExp()\n   {\n      return 'about|callto|ftp|gtalk|http|https|irc|ircs|javascript|mailto|mshelp|sftp|ssh|steam|tel|view-source|ymsgr'\n   }\n</code></pre>\n"}, {'answer_id': 11976301, 'author': 'baadf00d', 'author_id': 1577533, 'author_profile': 'https://Stackoverflow.com/users/1577533', 'pm_score': 4, 'selected': False, 'text': '<p>I needed a regular Expression to match all urls and made this one:</p>\n\n<pre><code>/(?:([^\\:]*)\\:\\/\\/)?(?:([^\\:\\@]*)(?:\\:([^\\@]*))?\\@)?(?:([^\\/\\:]*)\\.(?=[^\\.\\/\\:]*\\.[^\\.\\/\\:]*))?([^\\.\\/\\:]*)(?:\\.([^\\/\\.\\:]*))?(?:\\:([0-9]*))?(\\/[^\\?#]*(?=.*?\\/)\\/)?([^\\?#]*)?(?:\\?([^#]*))?(?:#(.*))?/\n</code></pre>\n\n<p>It matches all urls, any protocol, even urls like</p>\n\n<pre><code>ftp://user:pass@www.cs.server.com:8080/dir1/dir2/file.php?param1=value1#hashtag\n</code></pre>\n\n<p>The result (in JavaScript) looks like this:</p>\n\n<pre><code>["ftp", "user", "pass", "www.cs", "server", "com", "8080", "/dir1/dir2/", "file.php", "param1=value1", "hashtag"]\n</code></pre>\n\n<p>An url like</p>\n\n<pre><code>mailto://admin@www.cs.server.com\n</code></pre>\n\n<p>looks like this:</p>\n\n<pre><code>["mailto", "admin", undefined, "www.cs", "server", "com", undefined, undefined, undefined, undefined, undefined] \n</code></pre>\n'}, {'answer_id': 12470263, 'author': 'Rob', 'author_id': 203452, 'author_profile': 'https://Stackoverflow.com/users/203452', 'pm_score': 6, 'selected': False, 'text': "<p>I realize I'm late to the party, but there is a simple way to let the browser parse a url for you without a regex:</p>\n\n<pre><code>var a = document.createElement('a');\na.href = 'http://www.example.com:123/foo/bar.html?fox=trot#foo';\n\n['href','protocol','host','hostname','port','pathname','search','hash'].forEach(function(k) {\n    console.log(k+':', a[k]);\n});\n\n/*//Output:\nhref: http://www.example.com:123/foo/bar.html?fox=trot#foo\nprotocol: http:\nhost: www.example.com:123\nhostname: www.example.com\nport: 123\npathname: /foo/bar.html\nsearch: ?fox=trot\nhash: #foo\n*/\n</code></pre>\n"}, {'answer_id': 14057711, 'author': 'mjs', 'author_id': 961018, 'author_profile': 'https://Stackoverflow.com/users/961018', 'pm_score': 2, 'selected': False, 'text': '<p>Here is one that is complete, and doesnt rely on any protocol.</p>\n\n<pre><code>function getServerURL(url) {\n        var m = url.match("(^(?:(?:.*?)?//)?[^/?#;]*)");\n        console.log(m[1]) // Remove this\n        return m[1];\n    }\n\ngetServerURL("http://dev.test.se")\ngetServerURL("http://dev.test.se/")\ngetServerURL("//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js")\ngetServerURL("//")\ngetServerURL("www.dev.test.se/sdas/dsads")\ngetServerURL("www.dev.test.se/")\ngetServerURL("www.dev.test.se?abc=32")\ngetServerURL("www.dev.test.se#abc")\ngetServerURL("//dev.test.se?sads")\ngetServerURL("http://www.dev.test.se#321")\ngetServerURL("http://localhost:8080/sads")\ngetServerURL("https://localhost:8080?sdsa")\n</code></pre>\n\n<p><strong>Prints</strong></p>\n\n<pre><code>http://dev.test.se\n\nhttp://dev.test.se\n\n//ajax.googleapis.com\n\n//\n\nwww.dev.test.se\n\nwww.dev.test.se\n\nwww.dev.test.se\n\nwww.dev.test.se\n\n//dev.test.se\n\nhttp://www.dev.test.se\n\nhttp://localhost:8080\n\nhttps://localhost:8080\n</code></pre>\n'}, {'answer_id': 14385452, 'author': 'Skone', 'author_id': 158039, 'author_profile': 'https://Stackoverflow.com/users/158039', 'pm_score': 2, 'selected': False, 'text': "<p>None of the above worked for me.  Here's what I ended up using:</p>\n\n<pre><code>/^(?:((?:https?|s?ftp):)\\/\\/)([^:\\/\\s]+)(?::(\\d*))?(?:\\/([^\\s?#]+)?([?][^?#]*)?(#.*)?)?/\n</code></pre>\n"}, {'answer_id': 17892757, 'author': 'okigan', 'author_id': 142207, 'author_profile': 'https://Stackoverflow.com/users/142207', 'pm_score': 3, 'selected': False, 'text': "<p>Propose a much more readable solution (in Python, but applies to any regex):</p>\n\n<pre><code>def url_path_to_dict(path):\n    pattern = (r'^'\n               r'((?P&lt;schema&gt;.+?)://)?'\n               r'((?P&lt;user&gt;.+?)(:(?P&lt;password&gt;.*?))?@)?'\n               r'(?P&lt;host&gt;.*?)'\n               r'(:(?P&lt;port&gt;\\d+?))?'\n               r'(?P&lt;path&gt;/.*?)?'\n               r'(?P&lt;query&gt;[?].*?)?'\n               r'$'\n               )\n    regex = re.compile(pattern)\n    m = regex.match(path)\n    d = m.groupdict() if m is not None else None\n\n    return d\n\ndef main():\n    print url_path_to_dict('http://example.example.com/example/example/example.html')\n</code></pre>\n\n<p>Prints: </p>\n\n<pre><code>{\n'host': 'example.example.com', \n'user': None, \n'path': '/example/example/example.html', \n'query': None, \n'password': None, \n'port': None, \n'schema': 'http'\n}\n</code></pre>\n"}, {'answer_id': 24527267, 'author': 'Sam Adams', 'author_id': 1584651, 'author_profile': 'https://Stackoverflow.com/users/1584651', 'pm_score': 4, 'selected': False, 'text': '<p>I was trying to solve this in javascript, which should be handled by:</p>\n\n<pre><code>var url = new URL(\'http://a:b@example.com:890/path/wah@t/foo.js?foo=bar&amp;bingobang=&amp;king=kong@kong.com#foobar/bing/bo@ng?bang\');\n</code></pre>\n\n<p>since (in Chrome, at least) it parses to:</p>\n\n<pre><code>{\n  "hash": "#foobar/bing/bo@ng?bang",\n  "search": "?foo=bar&amp;bingobang=&amp;king=kong@kong.com",\n  "pathname": "/path/wah@t/foo.js",\n  "port": "890",\n  "hostname": "example.com",\n  "host": "example.com:890",\n  "password": "b",\n  "username": "a",\n  "protocol": "http:",\n  "origin": "http://example.com:890",\n  "href": "http://a:b@example.com:890/path/wah@t/foo.js?foo=bar&amp;bingobang=&amp;king=kong@kong.com#foobar/bing/bo@ng?bang"\n}\n</code></pre>\n\n<p>However, this isn\'t cross browser (<a href="https://developer.mozilla.org/en-US/docs/Web/API/URL" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/URL</a>), so I cobbled this together to pull the same parts out as above:</p>\n\n<pre><code>^(?:(?:(([^:\\/#\\?]+:)?(?:(?:\\/\\/)(?:(?:(?:([^:@\\/#\\?]+)(?:\\:([^:@\\/#\\?]*))?)@)?(([^:\\/#\\?\\]\\[]+|\\[[^\\/\\]@#?]+\\])(?:\\:([0-9]+))?))?)?)?((?:\\/?(?:[^\\/\\?#]+\\/+)*)(?:[^\\?#]*)))?(\\?[^#]+)?)(#.*)?\n</code></pre>\n\n<p>Credit for this regex goes to <a href="https://gist.github.com/rpflorence" rel="noreferrer">https://gist.github.com/rpflorence</a> who posted this jsperf <a href="http://jsperf.com/url-parsing" rel="noreferrer">http://jsperf.com/url-parsing</a> (originally found here: <a href="https://gist.github.com/jlong/2428561#comment-310066" rel="noreferrer">https://gist.github.com/jlong/2428561#comment-310066</a>) who came up with the regex this was originally based on.</p>\n\n<p>The parts are in this order:</p>\n\n<pre><code>var keys = [\n    "href",                    // http://user:pass@host.com:81/directory/file.ext?query=1#anchor\n    "origin",                  // http://user:pass@host.com:81\n    "protocol",                // http:\n    "username",                // user\n    "password",                // pass\n    "host",                    // host.com:81\n    "hostname",                // host.com\n    "port",                    // 81\n    "pathname",                // /directory/file.ext\n    "search",                  // ?query=1\n    "hash"                     // #anchor\n];\n</code></pre>\n\n<p>There is also a small library which wraps it and provides query params:</p>\n\n<p><a href="https://github.com/sadams/lite-url" rel="noreferrer">https://github.com/sadams/lite-url</a> (also available on bower)</p>\n\n<p>If you have an improvement, please create a pull request with more tests and I will accept and merge with thanks.</p>\n'}, {'answer_id': 26766402, 'author': 'jds', 'author_id': 1830334, 'author_profile': 'https://Stackoverflow.com/users/1830334', 'pm_score': 7, 'selected': False, 'text': '<p>I\'m a few years late to the party, but I\'m surprised no one has mentioned the Uniform Resource Identifier specification has a <a href="https://www.rfc-editor.org/rfc/rfc3986#appendix-B" rel="noreferrer">section on parsing URIs with a regular expression</a>. The regular expression, written by Berners-Lee, et al., is:</p>\n<blockquote>\n<pre><code>^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\n 12            3  4          5       6  7        8 9\n</code></pre>\n<p>The numbers in the second line above are only to assist readability;\nthey indicate the reference points for each subexpression (i.e., each\npaired parenthesis).  We refer to the value matched for subexpression\n as $.  For example, matching the above expression to</p>\n<p><code>http://www.ics.uci.edu/pub/ietf/uri/#Related</code></p>\n<p>results in the following subexpression matches:</p>\n<pre><code>$1 = http:\n$2 = http\n$3 = //www.ics.uci.edu\n$4 = www.ics.uci.edu\n$5 = /pub/ietf/uri/\n$6 = &lt;undefined&gt;\n$7 = &lt;undefined&gt;\n$8 = #Related\n$9 = Related\n</code></pre>\n</blockquote>\n<p>For what it\'s worth, I found that I had to escape the forward slashes in JavaScript:</p>\n<p><code>^(([^:\\/?#]+):)?(\\/\\/([^\\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?</code></p>\n'}, {'answer_id': 30563164, 'author': 'Yetti99', 'author_id': 3874595, 'author_profile': 'https://Stackoverflow.com/users/3874595', 'pm_score': 2, 'selected': False, 'text': '<p>I like the regex that was published in "Javascript: The Good Parts".\nIts not too short and not too complex.\nThis page on github also has the JavaScript code that uses it.\nBut it an be adapted for any language.\n<a href="https://gist.github.com/voodooGQ/4057330" rel="nofollow">https://gist.github.com/voodooGQ/4057330</a></p>\n'}, {'answer_id': 34451670, 'author': 'ylev', 'author_id': 3187132, 'author_profile': 'https://Stackoverflow.com/users/3187132', 'pm_score': -1, 'selected': False, 'text': '<pre><code>String s = "https://www.thomas-bayer.com/axis2/services/BLZService?wsdl";\n\nString regex = "(^http.?://)(.*?)([/\\\\?]{1,})(.*)";\n\nSystem.out.println("1: " + s.replaceAll(regex, "$1"));\nSystem.out.println("2: " + s.replaceAll(regex, "$2"));\nSystem.out.println("3: " + s.replaceAll(regex, "$3"));\nSystem.out.println("4: " + s.replaceAll(regex, "$4"));\n</code></pre>\n\n<p>Will provide the following output:<br>\n    1: https://<br>\n    2: www.thomas-bayer.com<br>\n    3: /<br>\n    4: axis2/services/BLZService?wsdl<br>\n<br>\nIf you change the URL to <br>\n    String s = "<a href="https://www.thomas-bayer.com?wsdl=qwerwer&amp;ttt=888" rel="nofollow">https://www.thomas-bayer.com?wsdl=qwerwer&amp;ttt=888</a>";\nthe output will be the following :<br>\n    1: https://<br>\n    2: www.thomas-bayer.com<br>\n    3: ?<br>\n    4: wsdl=qwerwer&amp;ttt=888<br></p>\n\n<p>enjoy..<br>\nYosi Lev</p>\n'}, {'answer_id': 39284990, 'author': 'Steve K', 'author_id': 2020820, 'author_profile': 'https://Stackoverflow.com/users/2020820', 'pm_score': 0, 'selected': False, 'text': '<p>The regex to do full parsing is quite horrendous. I\'ve included named backreferences for legibility, and broken each part into separate lines, but it still looks like this:</p>\n\n<pre><code>^(?:(?P&lt;protocol&gt;\\w+(?=:\\/\\/))(?::\\/\\/))?\n(?:(?P&lt;host&gt;(?:(?:&amp;(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^\\/?#:]+)(?::(?P&lt;port&gt;[0-9]+))?)\\/)?\n(?:(?P&lt;path&gt;(?:(?:&amp;(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)\\/)?\n(?P&lt;file&gt;(?:(?:&amp;(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)\n(?:\\?(?P&lt;querystring&gt;(?:(?:&amp;(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^#])+))?\n(?:#(?P&lt;fragment&gt;.*))?$\n</code></pre>\n\n<p>The thing that requires it to be so verbose is that except for the protocol or the port, any of the parts can contain HTML entities, which makes delineation of the fragment quite tricky. So in the last few cases - the host, path, file, querystring, and fragment, we allow either any html entity or any character that isn\'t a <code>?</code> or <code>#</code>. The regex for an html entity looks like this:</p>\n\n<pre><code>$htmlentity = "&amp;(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);"\n</code></pre>\n\n<p>When that is extracted (I used a mustache syntax to represent it), it becomes a bit more legible:</p>\n\n<pre><code>^(?:(?P&lt;protocol&gt;(?:ht|f)tps?|\\w+(?=:\\/\\/))(?::\\/\\/))?\n(?:(?P&lt;host&gt;(?:{{htmlentity}}|[^\\/?#:])+(?::(?P&lt;port&gt;[0-9]+))?)\\/)?\n(?:(?P&lt;path&gt;(?:{{htmlentity}}|[^?#])+)\\/)?\n(?P&lt;file&gt;(?:{{htmlentity}}|[^?#])+)\n(?:\\?(?P&lt;querystring&gt;(?:{{htmlentity}};|[^#])+))?\n(?:#(?P&lt;fragment&gt;.*))?$\n</code></pre>\n\n<p>In JavaScript, of course, you can\'t use named backreferences, so the regex becomes</p>\n\n<pre><code>^(?:(\\w+(?=:\\/\\/))(?::\\/\\/))?(?:((?:(?:&amp;(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^\\/?#:]+)(?::([0-9]+))?)\\/)?(?:((?:(?:&amp;(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)\\/)?((?:(?:&amp;(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)(?:\\?((?:(?:&amp;(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^#])+))?(?:#(.*))?$\n</code></pre>\n\n<p>and in each match, the protocol is <code>\\1</code>, the host is <code>\\2</code>, the port is <code>\\3</code>, the path <code>\\4</code>, the file <code>\\5</code>, the querystring <code>\\6</code>, and the fragment <code>\\7</code>.</p>\n'}, {'answer_id': 40766359, 'author': 'Gil Zellner', 'author_id': 1889311, 'author_profile': 'https://Stackoverflow.com/users/1889311', 'pm_score': 1, 'selected': False, 'text': '<p>I tried a few of these that didn\'t cover my needs, especially the highest voted which didn\'t catch a url without a path (<a href="http://example.com/" rel="nofollow noreferrer">http://example.com/</a>)</p>\n\n<p>also lack of group names made it unusable in ansible (or perhaps my jinja2 skills are lacking).</p>\n\n<p>so this is my version slightly modified with the source being the highest voted version here:</p>\n\n<pre><code>^((?P&lt;protocol&gt;http[s]?|ftp):\\/)?\\/?(?P&lt;host&gt;[^:\\/\\s]+)(?P&lt;path&gt;((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+))*(.*)?(#[\\w\\-]+)?$\n</code></pre>\n'}, {'answer_id': 45708666, 'author': 'mohan mu', 'author_id': 7745445, 'author_profile': 'https://Stackoverflow.com/users/7745445', 'pm_score': 0, 'selected': False, 'text': '<pre><code>//USING REGEX\n/**\n * Parse URL to get information\n *\n * @param   url     the URL string to parse\n * @return  parsed  the URL parsed or null\n */\nvar UrlParser = function (url) {\n    "use strict";\n\n    var regx = /^(((([^:\\/#\\?]+:)?(?:(\\/\\/)((?:(([^:@\\/#\\?]+)(?:\\:([^:@\\/#\\?]+))?)@)?(([^:\\/#\\?\\]\\[]+|\\[[^\\/\\]@#?]+\\])(?:\\:([0-9]+))?))?)?)?((\\/?(?:[^\\/\\?#]+\\/+)*)([^\\?#]*)))?(\\?[^#]+)?)(#.*)?/,\n        matches = regx.exec(url),\n        parser = null;\n\n    if (null !== matches) {\n        parser = {\n            href              : matches[0],\n            withoutHash       : matches[1],\n            url               : matches[2],\n            origin            : matches[3],\n            protocol          : matches[4],\n            protocolseparator : matches[5],\n            credhost          : matches[6],\n            cred              : matches[7],\n            user              : matches[8],\n            pass              : matches[9],\n            host              : matches[10],\n            hostname          : matches[11],\n            port              : matches[12],\n            pathname          : matches[13],\n            segment1          : matches[14],\n            segment2          : matches[15],\n            search            : matches[16],\n            hash              : matches[17]\n        };\n    }\n\n    return parser;\n};\n\nvar parsedURL=UrlParser(url);\nconsole.log(parsedURL);\n</code></pre>\n'}, {'answer_id': 63028949, 'author': 'Bilal Demir', 'author_id': 9082736, 'author_profile': 'https://Stackoverflow.com/users/9082736', 'pm_score': 0, 'selected': False, 'text': '<p>I tried this regex for parsing url partitions:</p>\n<pre><code>^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:([^\\/]*))?((\\/?(?:[^\\/\\?#]+\\/+)*)([^\\?#]*))(\\?([^#]*))?(#(.*))?$\n</code></pre>\n<p>URL: <code>https://www.google.com/my/path/sample/asd-dsa/this?key1=value1&amp;key2=value2</code></p>\n<p>Matches:</p>\n<pre><code>Group 1.    0-7 https:/\nGroup 2.    0-5 https\nGroup 3.    8-22    www.google.com\nGroup 6.    22-50   /my/path/sample/asd-dsa/this\nGroup 7.    22-46   /my/path/sample/asd-dsa/\nGroup 8.    46-50   this\nGroup 9.    50-74   ?key1=value1&amp;key2=value2\nGroup 10.   51-74   key1=value1&amp;key2=value2\n</code></pre>\n'}, {'answer_id': 64468826, 'author': 'CallMarl', 'author_id': 5540407, 'author_profile': 'https://Stackoverflow.com/users/5540407', 'pm_score': 1, 'selected': False, 'text': "<p>I build this one. Very permissive it's not to check url juste divide it.</p>\n<p><code>^((http[s]?):\\/\\/)?([a-zA-Z0-9-.]*)?([\\/]?[^?#\\n]*)?([?]?[^?#\\n]*)?([#]?[^?#\\n]*)$</code></p>\n<ul>\n<li>match 1 : full protocole with :// (http or https)</li>\n<li>match 2 : protocole without ://</li>\n<li>match 3 : host</li>\n<li>match 4 : slug</li>\n<li>match 5 : param</li>\n<li>match 6 : anchor</li>\n</ul>\n<p><strong>work</strong></p>\n<pre><code>http://\nhttps://\nwww.demo.com\n/slug\n?foo=bar\n#anchor\n\nhttps://demo.com\nhttps://demo.com/\nhttps://demo.com/slug\nhttps://demo.com/slug/foo\nhttps://demo.com/?foo=bar\nhttps://demo.com/?foo=bar#anchor\nhttps://demo.com/?foo=bar&amp;bar=foo#anchor\nhttps://www.greate-demo.com/\n</code></pre>\n<p><strong>crash</strong></p>\n<pre><code>#anchor#\n?toto?\n</code></pre>\n"}, {'answer_id': 65070175, 'author': 'Hritik Soni', 'author_id': 5113528, 'author_profile': 'https://Stackoverflow.com/users/5113528', 'pm_score': 0, 'selected': False, 'text': "<p>The best answer suggested here didn't work for me because my URLs also contain a port.\nHowever modifying it to the following regex worked for me:</p>\n<pre><code>^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:\\d+)?((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(.*)?(#[\\w\\-]+)?$\n</code></pre>\n"}, {'answer_id': 67148884, 'author': 'igorzg', 'author_id': 3053382, 'author_profile': 'https://Stackoverflow.com/users/3053382', 'pm_score': 3, 'selected': False, 'text': '<pre><code>const URI_RE = /^(([^:\\/\\s]+):\\/?\\/?([^\\/\\s@]*@)?([^\\/@:]*)?:?(\\d+)?)?(\\/[^?]*)?(\\?([^#]*))?(#[\\s\\S]*)?$/;\n/**\n* GROUP 1 ([scheme][authority][host][port])\n* GROUP 2 (scheme)\n* GROUP 3 (authority)\n* GROUP 4 (host)\n* GROUP 5 (port)\n* GROUP 6 (path)\n* GROUP 7 (?query)\n* GROUP 8 (query)\n* GROUP 9 (fragment)\n*/\nURI_RE.exec(&quot;https://john:doe@www.example.com:123/forum/questions/?tag=networking&amp;order=newest#top&quot;);\nURI_RE.exec(&quot;/forum/questions/?tag=networking&amp;order=newest#top&quot;);\nURI_RE.exec(&quot;ldap://[2001:db8::7]/c=GB?objectClass?one&quot;);\nURI_RE.exec(&quot;mailto:John.Doe@example.com&quot;);\n</code></pre>\n<p>Above you can find javascript implementation with modified regex</p>\n'}, {'answer_id': 67796005, 'author': 'MattWeiler', 'author_id': 1827349, 'author_profile': 'https://Stackoverflow.com/users/1827349', 'pm_score': 1, 'selected': False, 'text': "<p>I needed some REGEX to parse the components of a URL in Java.\nThis is what I'm using:</p>\n<pre><code>&quot;^(?:(http[s]?|ftp):/)?/?&quot; +    // METHOD\n&quot;([^:^/^?^#\\\\s]+)&quot; +            // HOSTNAME\n&quot;(?::(\\\\d+))?&quot; +                // PORT\n&quot;([^?^#.*]+)?&quot; +                // PATH\n&quot;(\\\\?[^#.]*)?&quot; +                // QUERY\n&quot;(#[\\\\w\\\\-]+)?$&quot;                // ID\n</code></pre>\n<p><strong>Java Code Snippet:</strong></p>\n<pre><code>final Pattern pattern = Pattern.compile(\n        &quot;^(?:(http[s]?|ftp):/)?/?&quot; +    // METHOD\n        &quot;([^:^/^?^#\\\\s]+)&quot; +            // HOSTNAME\n        &quot;(?::(\\\\d+))?&quot; +                // PORT\n        &quot;([^?^#.*]+)?&quot; +                // PATH\n        &quot;(\\\\?[^#.]*)?&quot; +                // QUERY\n        &quot;(#[\\\\w\\\\-]+)?$&quot;                // ID\n);\nfinal Matcher matcher = pattern.matcher(url);\n\nSystem.out.println(&quot;     URL: &quot; + url);\n\nif (matcher.matches())\n{\n    System.out.println(&quot;  Method: &quot; + matcher.group(1));\n    System.out.println(&quot;Hostname: &quot; + matcher.group(2));\n    System.out.println(&quot;    Port: &quot; + matcher.group(3));\n    System.out.println(&quot;    Path: &quot; + matcher.group(4));\n    System.out.println(&quot;   Query: &quot; + matcher.group(5));\n    System.out.println(&quot;      ID: &quot; + matcher.group(6));\n    \n    return matcher.group(2);\n}\n\nSystem.out.println();\nSystem.out.println();\n</code></pre>\n"}, {'answer_id': 70326445, 'author': 'Exo Flame', 'author_id': 4530300, 'author_profile': 'https://Stackoverflow.com/users/4530300', 'pm_score': 0, 'selected': False, 'text': '<p>For browser / nodejs environment there is a built in URL class which share the same signature it seems. but check out the respective focus for your case.</p>\n<p><a href="https://nodejs.org/api/url.html#urlhost" rel="nofollow noreferrer">https://nodejs.org/api/url.html#urlhost</a></p>\n<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/URL" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/URL</a></p>\n<p>This is how it may be used though.</p>\n<pre><code>let url = new URL(\'https://test.example.com/cats?name=foofy\')\nurl.protocall; // https:\nurl.hostname; // test.example.com\nurl.pathname; // /cats\nurl.search; // ?name=foofy\n\nlet params = url.searchParams\nlet name = params.get(\'name\');// always string I think so parse accordingly\n\n</code></pre>\n<p>for more on parameters also see <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams</a></p>\n'}]
['https://Stackoverflow.com/questions/27745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2644/']