URL 连接字符串的正则表达式 [英] Regex for a URL Connection String

查看:46
本文介绍了URL 连接字符串的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有已知的 JavaScript 正则表达式来匹配整个 URL 连接字符串?

Is there a known JavaScript regular expression to match an entire URL Connection String?

protocol://user:password@hostname:12345/segment1/segment2?p1=val1&p2=val2

我正在寻找一个可以帮助我将这样的连接字符串转换为对象的正则表达式:

I'm looking for a single regular expression that would help me translate such a connection string into an object:

{
    protocol: 'protocol',
    user: 'user',
    password: 'password',
    host: 'hostname:12345',
    hostname: 'hostname',
    port: 12345,
    segments: ['segment1', 'segment2'],
    params: {
        p1: 'val1',
        p2: 'val2'
    }
}

此外,我希望连接字符串的每个部分都是可选的,因此可以使用环境中的值填充缺失的参数.

Also, I want every single part of the connection string to be optional, so the missing parameters can be filled by values from the environment.

示例:

  • protocol://
  • server:12345
  • :12345 - 仅用于端口
  • user:password@
  • user@
  • :password@
  • /segment1
  • ?p1=val1
  • 等等...

标准 RFC 3986 规则应适用于所有部分有效符号.

Standard RFC 3986 rules should apply to all the parts when it comes to the valid symbols.

我正在寻找适用于 Node.js 和所有浏览器的东西.

I'm looking for something that would work in both Node.js and all browsers.

我在 connection-string,但问题是它不允许验证,即判断整个事情是否有效.

I've done a separate parsing piece-by-piece within connection-string, but the problem with that - it doesn't allow to validate, i.e. to tell if the whole thing is valid.

推荐答案

类似这样的事情?

function url2obj(url) {
    var pattern = /^(?:([^:\/?#\s]+):\/{2})?(?:([^@\/?#\s]+)@)?([^\/?#\s]+)?(?:\/([^?#\s]*))?(?:[?]([^#\s]+))?\S*$/;
    var matches =  url.match(pattern);
    var params = {};
    if (matches[5] != undefined) { 
       matches[5].split('&').map(function(x){
         var a = x.split('=');
         params[a[0]]=a[1];
       });
    }

    return {
        protocol: matches[1],
        user: matches[2] != undefined ? matches[2].split(':')[0] : undefined,
        password: matches[2] != undefined ? matches[2].split(':')[1] : undefined,
        host: matches[3],
        hostname: matches[3] != undefined ? matches[3].split(/:(?=\d+$)/)[0] : undefined,
        port: matches[3] != undefined ? matches[3].split(/:(?=\d+$)/)[1] : undefined,
        segments : matches[4] != undefined ? matches[4].split('/') : undefined,
        params: params 
    };
}

console.log(url2obj("protocol://user:password@hostname:12345/segment1/segment2?p1=val1&p2=val2"));
console.log(url2obj("http://hostname"));
console.log(url2obj(":password@"));
console.log(url2obj("?p1=val1"));
console.log(url2obj("ftp://usr:pwd@[FFF::12]:345/testIP6"));

对正则表达式模式的测试 这里是 regex101

A test for the regex pattern here on regex101

这篇关于URL 连接字符串的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆