Programing

URL의 일부 가져 오기 (정규식)

lottogame 2020. 7. 4. 10:36
반응형

URL의 일부 가져 오기 (정규식)


주어진 URL (한 줄) :
http://test.example.com/dir/subdir/file.html

정규식을 사용하여 다음 부분을 추출하는 방법 :

  1. 하위 도메인 (테스트)
  2. 도메인 (example.com)
  3. 파일이없는 경로 (/ dir / subdir /)
  4. 파일 (file.html)
  5. 파일이있는 경로 (/dir/subdir/file.html)
  6. 경로가없는 URL ( http://test.example.com )
  7. (유용하다고 생각되는 다른 것을 추가하십시오)

다음 URL을 입력해도 정규식이 올바르게 작동합니다.

http://example.example.com/example/example/example.html

쿼리 매개 변수 및 앵커를 포함하여 전체 URL을 구문 분석하고 분류하는 단일 정규식

https://www.google.com/dir/1/2/search.html?arg=0-a&arg1=1-b&arg3-c#hash

^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$

RexEx 포지션 :

url : RegExp [ '$ &'],

프로토콜 : RegExp. $ 2,

호스트 : RegExp. $ 3,

경로 : RegExp. $ 4,

파일 : RegExp. $ 6,

query : RegExp. $ 7,

해시 : RegExp. $ 8

그런 다음 호스트를 더욱 쉽게 구문 분석 할 수 있습니다 ( '.'구분).

어떻게 내가 할 것이라고는이 같은 사용 무언가이다 :

/*
    ^(.*:)//([A-Za-z0-9\-\.]+)(:[0-9]+)?(.*)$
*/
proto $1
host $2
port $3
the-rest $4

추가 구문 분석 '나머지'는 가능한 한 구체적이어야합니다. 하나의 정규식에서하는 것은 약간 미친 것입니다.


나는 파티에 늦었다는 것을 알고 있지만 정규 표현식없이 브라우저가 URL을 구문 분석 할 수있는 간단한 방법이 있습니다.

var a = document.createElement('a');
a.href = 'http://www.example.com:123/foo/bar.html?fox=trot#foo';

['href','protocol','host','hostname','port','pathname','search','hash'].forEach(function(k) {
    console.log(k+':', a[k]);
});

/*//Output:
href: http://www.example.com:123/foo/bar.html?fox=trot#foo
protocol: http:
host: www.example.com:123
hostname: www.example.com
port: 123
pathname: /foo/bar.html
search: ?fox=trot
hash: #foo
*/

나는 파티에 몇 년 늦었지만, 아무도 URI ( Uniform Resource Identifier) ​​사양 에 정규 표현식을 사용하여 URI 구문 분석에 대한 섹션 이 있다고 언급 한 것이 놀랍다 . Berners-Lee 등이 작성한 정규식은 다음과 같습니다.

^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
 12            3  4          5       6  7        8 9

위의 두 번째 줄에있는 숫자는 가독성을 돕기위한 것입니다. 그것들은 각 부분 표현에 대한 기준점을 나타낸다 (즉, 각 쌍 괄호). 하위 표현식에 일치하는 값을 $라고합니다. 예를 들어 위의 표현식을

http://www.ics.uci.edu/pub/ietf/uri/#Related

다음과 같은 하위 표현식이 일치합니다.

$1 = http:
$2 = http
$3 = //www.ics.uci.edu
$4 = www.ics.uci.edu
$5 = /pub/ietf/uri/
$6 = <undefined>
$7 = <undefined>
$8 = #Related
$9 = Related

가치있는 것을 위해 JavaScript에서 슬래시를 피해야한다는 것을 알았습니다.

^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?


나는 가장 높은 투표 응답 (hometoast의 답변)이 완벽하게 작동하지 않는다는 것을 알았습니다. 두 가지 문제 :

  1. 포트 번호를 처리 할 수 ​​없습니다.
  2. 해시 부분이 손상되었습니다.

다음은 수정 된 버전입니다.

^((http[s]?|ftp):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?$

부품의 위치는 다음과 같습니다.

int SCHEMA = 2, DOMAIN = 3, PORT = 5, PATH = 6, FILE = 8, QUERYSTRING = 9, HASH = 12

익명 사용자가 게시 한 편집 :

function getFileName(path) {
    return path.match(/^((http[s]?|ftp):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/[\w\/-]+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?$/i)[8];
}

모든 URL과 일치하는 정규식이 필요했고 이것을 만들었습니다.

/(?:([^\:]*)\:\/\/)?(?:([^\:\@]*)(?:\:([^\@]*))?\@)?(?:([^\/\:]*)\.(?=[^\.\/\:]*\.[^\.\/\:]*))?([^\.\/\:]*)(?:\.([^\/\.\:]*))?(?:\:([0-9]*))?(\/[^\?#]*(?=.*?\/)\/)?([^\?#]*)?(?:\?([^#]*))?(?:#(.*))?/

그것은 모든 URL, 모든 프로토콜, 심지어 같은 URL과 일치합니다.

ftp://user:pass@www.cs.server.com:8080/dir1/dir2/file.php?param1=value1#hashtag

결과 (JavaScript)는 다음과 같습니다.

["ftp", "user", "pass", "www.cs", "server", "com", "8080", "/dir1/dir2/", "file.php", "param1=value1", "hashtag"]

같은 URL

mailto://admin@www.cs.server.com

다음과 같이 보입니다 :

["mailto", "admin", undefined, "www.cs", "server", "com", undefined, undefined, undefined, undefined, undefined] 

나는 이것을 자바 스크립트로 해결하려고 노력했다.

var url = new URL('http://a:b@example.com:890/path/wah@t/foo.js?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang');

(Chrome에서는) 다음과 같이 구문 분석합니다.

{
  "hash": "#foobar/bing/bo@ng?bang",
  "search": "?foo=bar&bingobang=&king=kong@kong.com",
  "pathname": "/path/wah@t/foo.js",
  "port": "890",
  "hostname": "example.com",
  "host": "example.com:890",
  "password": "b",
  "username": "a",
  "protocol": "http:",
  "origin": "http://example.com:890",
  "href": "http://a:b@example.com:890/path/wah@t/foo.js?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang"
}

그러나 이것은 크로스 브라우저 ( https://developer.mozilla.org/en-US/docs/Web/API/URL )가 아니므로 위와 같이 동일한 부분을 꺼내기 위해 이것을 고쳤습니다.

^(?:(?:(([^:\/#\?]+:)?(?:(?:\/\/)(?:(?:(?:([^:@\/#\?]+)(?:\:([^:@\/#\?]*))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((?:\/?(?:[^\/\?#]+\/+)*)(?:[^\?#]*)))?(\?[^#]+)?)(#.*)?

이 정규식에 대한 신용 간다 https://gist.github.com/rpflorence 이 jsperf 게시 사람 http://jsperf.com/url-parsing 여기에 원래 발견을 (: https://gist.github.com/jlong/2428561 # comment-310066 )이 정규 표현식을 처음으로 작성한 사람입니다.

부품 순서는 다음과 같습니다.

var keys = [
    "href",                    // http://user:pass@host.com:81/directory/file.ext?query=1#anchor
    "origin",                  // http://user:pass@host.com:81
    "protocol",                // http:
    "username",                // user
    "password",                // pass
    "host",                    // host.com:81
    "hostname",                // host.com
    "port",                    // 81
    "pathname",                // /directory/file.ext
    "search",                  // ?query=1
    "hash"                     // #anchor
];

그것을 감싸고 쿼리 매개 변수를 제공하는 작은 라이브러리도 있습니다.

https://github.com/sadams/lite-url (또는 bower에서도 사용 가능)

개선이 있다면 더 많은 테스트로 끌어 오기 요청을 작성하십시오. 감사합니다.


훨씬 더 읽기 쉬운 솔루션을 제안하십시오 (Python에서는 정규식에 적용됨).

def url_path_to_dict(path):
    pattern = (r'^'
               r'((?P<schema>.+?)://)?'
               r'((?P<user>.+?)(:(?P<password>.*?))?@)?'
               r'(?P<host>.*?)'
               r'(:(?P<port>\d+?))?'
               r'(?P<path>/.*?)?'
               r'(?P<query>[?].*?)?'
               r'$'
               )
    regex = re.compile(pattern)
    m = regex.match(path)
    d = m.groupdict() if m is not None else None

    return d

def main():
    print url_path_to_dict('http://example.example.com/example/example/example.html')

인쇄물:

{
'host': 'example.example.com', 
'user': None, 
'path': '/example/example/example.html', 
'query': None, 
'password': None, 
'port': None, 
'schema': 'http'
}

하위 도메인과 도메인은 하위 도메인이 최상위 도메인 인 http://sub1.sub2.domain.co.uk/ 와 같이 여러 부분을 가질 수 있으므로 어렵습니다 .

 the path without the file : http://[^/]+/((?:[^/]+/)*(?:[^/]+$)?)  
 the file : http://[^/]+/(?:[^/]+/)*((?:[^/.]+\.)+[^/.]+)$  
 the path with the file : http://[^/]+/(.*)  
 the URL without the path : (http://[^/]+/)  

(마크 다운은 정규 표현식에 그리 친절하지 않습니다)


이 향상된 버전은 파서처럼 안정적으로 작동해야합니다.

   // Applies to URI, not just URL or URN:
   //    http://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Relationship_to_URL_and_URN
   //
   // http://labs.apache.org/webarch/uri/rfc/rfc3986.html#regexp
   //
   // (?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?
   //
   // http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax
   //
   // $@ matches the entire uri
   // $1 matches scheme (ftp, http, mailto, mshelp, ymsgr, etc)
   // $2 matches authority (host, user:pwd@host, etc)
   // $3 matches path
   // $4 matches query (http GET REST api, etc)
   // $5 matches fragment (html anchor, etc)
   //
   // Match specific schemes, non-optional authority, disallow white-space so can delimit in text, and allow 'www.' w/o scheme
   // Note the schemes must match ^[^\s|:/?#]+(?:\|[^\s|:/?#]+)*$
   //
   // (?:()(www\.[^\s/?#]+\.[^\s/?#]+)|(schemes)://([^\s/?#]*))([^\s?#]*)(?:\?([^\s#]*))?(#(\S*))?
   //
   // Validate the authority with an orthogonal RegExp, so the RegExp above won’t fail to match any valid urls.
   function uriRegExp( flags, schemes/* = null*/, noSubMatches/* = false*/ )
   {
      if( !schemes )
         schemes = '[^\\s:\/?#]+'
      else if( !RegExp( /^[^\s|:\/?#]+(?:\|[^\s|:\/?#]+)*$/ ).test( schemes ) )
         throw TypeError( 'expected URI schemes' )
      return noSubMatches ? new RegExp( '(?:www\\.[^\\s/?#]+\\.[^\\s/?#]+|' + schemes + '://[^\\s/?#]*)[^\\s?#]*(?:\\?[^\\s#]*)?(?:#\\S*)?', flags ) :
         new RegExp( '(?:()(www\\.[^\\s/?#]+\\.[^\\s/?#]+)|(' + schemes + ')://([^\\s/?#]*))([^\\s?#]*)(?:\\?([^\\s#]*))?(?:#(\\S*))?', flags )
   }

   // http://en.wikipedia.org/wiki/URI_scheme#Official_IANA-registered_schemes
   function uriSchemesRegExp()
   {
      return 'about|callto|ftp|gtalk|http|https|irc|ircs|javascript|mailto|mshelp|sftp|ssh|steam|tel|view-source|ymsgr'
   }

다음을 시도하십시오 :

^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?

HTTP / FTP, 하위 도메인, 폴더, 파일 등을 지원합니다.

빠른 Google 검색에서 찾았습니다.

http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx


/^((?P<scheme>https?|ftp):\/)?\/?((?P<username>.*?)(:(?P<password>.*?)|)@)?(?P<hostname>[^:\/\s]+)(?P<port>:([^\/]*))?(?P<path>(\/\w+)*\/)(?P<filename>[-\w.]+[^#?\s]*)?(?P<query>\?([^#]*))?(?P<fragment>#(.*))?$/

비슷한 질문 에 대한 내 대답에서 . 언급 된 다른 버그 중 일부 버그 (예 : 사용자 이름 / 암호를 지원하지 않고 단일 문자 파일 이름을 지원하지 않음, 조각 식별자가 손상됨) 때문에 더 잘 작동합니다.


.NET에서 Uri 객체를 사용하여 모든 http / https, 호스트, 포트, 경로 및 쿼리를 얻을 수 있습니다. 어려운 작업은 호스트를 하위 도메인, 도메인 이름 및 TLD로 나누는 것입니다.

그렇게하는 표준은 없으며 단순히 문자열 구문 분석 또는 RegEx를 사용하여 올바른 결과를 생성 할 수 없습니다. 처음에는 RegEx 기능을 사용하고 있지만 모든 URL이 하위 도메인을 올바르게 구문 분석 할 수는 없습니다. 실제 방법은 TLD 목록을 사용하는 것입니다. URL에 대한 TLD가 정의 된 후 왼쪽 부분은 도메인이고 나머지 부분은 하위 도메인입니다.

그러나 새로운 TLD가 가능하므로 목록을 유지해야합니다. 내가 알고있는 현재 순간은 publicsuffix.org입니다. 최신 목록을 유지하고 Google 코드의 domainname-parser 도구를 사용하여 공개 접미사 목록을 구문 분석하고 DomainName 객체를 사용하여 하위 도메인, 도메인 및 TLD를 쉽게 얻을 수 있습니다 : domainName.SubDomain, domainName .Domain 및 domainName.TLD.

이 답변도 도움이됩니다 : URL에서 하위 도메인 가져 오기

칼 멜란


다음은 완전하며 프로토콜에 의존하지 않는 것입니다.

function getServerURL(url) {
        var m = url.match("(^(?:(?:.*?)?//)?[^/?#;]*)");
        console.log(m[1]) // Remove this
        return m[1];
    }

getServerURL("http://dev.test.se")
getServerURL("http://dev.test.se/")
getServerURL("//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js")
getServerURL("//")
getServerURL("www.dev.test.se/sdas/dsads")
getServerURL("www.dev.test.se/")
getServerURL("www.dev.test.se?abc=32")
getServerURL("www.dev.test.se#abc")
getServerURL("//dev.test.se?sads")
getServerURL("http://www.dev.test.se#321")
getServerURL("http://localhost:8080/sads")
getServerURL("https://localhost:8080?sdsa")

인쇄물

http://dev.test.se

http://dev.test.se

//ajax.googleapis.com

//

www.dev.test.se

www.dev.test.se

www.dev.test.se

www.dev.test.se

//dev.test.se

http://www.dev.test.se

http://localhost:8080

https://localhost:8080

위의 어느 것도 나를 위해 일하지 않았습니다. 내가 사용한 결과는 다음과 같습니다.

/^(?:((?:https?|s?ftp):)\/\/)([^:\/\s]+)(?::(\d*))?(?:\/([^\s?#]+)?([?][^?#]*)?(#.*)?)?/

"Javascript : The Good Parts"에 게시 된 정규식이 마음에 듭니다. 너무 짧지 않고 너무 복잡하지 않습니다. github의이 페이지에는이를 사용하는 JavaScript 코드가 있습니다. 그러나 모든 언어에 적용 할 수 있습니다. https://gist.github.com/voodooGQ/4057330


Java는이를 수행 할 URL 클래스를 제공합니다. URL 객체 쿼리.

참고로 PHP는 parse_url ()을 제공합니다 .


정규식을 사용하지 않는 것이 좋습니다. WinHttpCrackUrl () 과 같은 API 호출 은 오류가 덜 발생합니다.

http://msdn.microsoft.com/en-us/library/aa384092%28VS.85%29.aspx


나는 내 요구를 충족시키지 못하는 몇 가지, 특히 경로가없는 URL을 잡지 않은 가장 높은 투표를 시도했습니다 ( http://example.com/ )

또한 그룹 이름이 부족하여 사용할 수 없게 만들었습니다 (또는 아마도 jinja2 기술이 부족합니다).

그래서 이것은 내 버전이 약간 수정되어 소스가 가장 높은 투표 버전입니다.

^((?P<protocol>http[s]?|ftp):\/)?\/?(?P<host>[^:\/\s]+)(?P<path>((\/\w+)*\/)([\w\-\.]+[^#?\s]+))*(.*)?(#[\w\-]+)?$

http://www.fileformat.info/tool/regex.htm hometoast의 정규식을 사용하면 효과적입니다.

그러나 여기에 거래가 있습니다. 프로그램의 상황에 따라 다른 정규식 패턴을 사용하고 싶습니다.

예를 들어이 URL이 있고 프로그램에서 지원되는 모든 URL을 나열하는 열거 형이 있습니다. 열거의 각 객체에는 getRegexPattern 메소드가 있는데,이 메소드는 정규식 패턴을 반환하고 URL과 비교하는 데 사용됩니다. 특정 정규식 패턴이 true를 반환하면이 URL이 내 프로그램에서 지원된다는 것을 알고 있습니다. 따라서 각 열거 형은 URL 내부에서 볼 위치에 따라 자체 정규 표현식을 갖습니다.

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).

That is why I wanted the answer to give the regex for each situation separately. Although +1 for hometoast. ;)


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?

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:

(?:SOMESTUFF)

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 as part of a URL. 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.

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:

https?

would match 'http' or 'https' just fine.


regexp to get the URL path without the file.

url = 'http://domain/dir1/dir2/somefile' url.scan(/^(http://[^/]+)((?:/[^/]+)+(?=/))?/?(?:[^/]+)?$/i).to_s

It can be useful for adding a relative path to this url.


String s = "https://www.thomas-bayer.com/axis2/services/BLZService?wsdl";

String regex = "(^http.?://)(.*?)([/\\?]{1,})(.*)";

System.out.println("1: " + s.replaceAll(regex, "$1"));
System.out.println("2: " + s.replaceAll(regex, "$2"));
System.out.println("3: " + s.replaceAll(regex, "$3"));
System.out.println("4: " + s.replaceAll(regex, "$4"));

Will provide the following output:
1: https://
2: www.thomas-bayer.com
3: /
4: axis2/services/BLZService?wsdl

If you change the URL to
String s = "https://www.thomas-bayer.com?wsdl=qwerwer&ttt=888"; the output will be the following :
1: https://
2: www.thomas-bayer.com
3: ?
4: wsdl=qwerwer&ttt=888

enjoy..
Yosi Lev


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<protocol>\w+(?=:\/\/))(?::\/\/))?
(?:(?P<host>(?:(?:&(?: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<port>[0-9]+))?)\/)?
(?:(?P<path>(?:(?:&(?: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<file>(?:(?:&(?: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<querystring>(?:(?:&(?: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<fragment>.*))?$

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 ? or #. The regex for an html entity looks like this:

$htmlentity = "&(?: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]+);"

When that is extracted (I used a mustache syntax to represent it), it becomes a bit more legible:

^(?:(?P<protocol>(?:ht|f)tps?|\w+(?=:\/\/))(?::\/\/))?
(?:(?P<host>(?:{{htmlentity}}|[^\/?#:])+(?::(?P<port>[0-9]+))?)\/)?
(?:(?P<path>(?:{{htmlentity}}|[^?#])+)\/)?
(?P<file>(?:{{htmlentity}}|[^?#])+)
(?:\?(?P<querystring>(?:{{htmlentity}};|[^#])+))?
(?:#(?P<fragment>.*))?$

In JavaScript, of course, you can't use named backreferences, so the regex becomes

^(?:(\w+(?=:\/\/))(?::\/\/))?(?:((?:(?:&(?: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|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|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|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]+);)|[^#])+))?(?:#(.*))?$

and in each match, the protocol is \1, the host is \2, the port is \3, the path \4, the file \5, the querystring \6, and the fragment \7.


//USING REGEX
/**
 * Parse URL to get information
 *
 * @param   url     the URL string to parse
 * @return  parsed  the URL parsed or null
 */
var UrlParser = function (url) {
    "use strict";

    var regx = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
        matches = regx.exec(url),
        parser = null;

    if (null !== matches) {
        parser = {
            href              : matches[0],
            withoutHash       : matches[1],
            url               : matches[2],
            origin            : matches[3],
            protocol          : matches[4],
            protocolseparator : matches[5],
            credhost          : matches[6],
            cred              : matches[7],
            user              : matches[8],
            pass              : matches[9],
            host              : matches[10],
            hostname          : matches[11],
            port              : matches[12],
            pathname          : matches[13],
            segment1          : matches[14],
            segment2          : matches[15],
            search            : matches[16],
            hash              : matches[17]
        };
    }

    return parser;
};

var parsedURL=UrlParser(url);
console.log(parsedURL);

참고URL : https://stackoverflow.com/questions/27745/getting-parts-of-a-url-regex

반응형