这是Uri。IsWellFormedUriString和Uri。TryCreate方法,但它们似乎为文件路径返回true,等等。

我如何检查字符串是否是一个有效的(不一定是活动的)HTTP URL用于输入验证目的?


当前回答

    public static bool CheckURLValid(this string source)
    {
        Uri uriResult;
        return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
    }

用法:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}

更新:(单行代码)谢谢@GoClimbColorado

public static bool CheckURLValid(this string source) => Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps;

用法:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}

其他回答

我创建了这个函数来帮助我进行URL验证,你可以根据自己的喜好定制它,注意这是用python3.10.6编写的

def url_validator(url: str) -> bool:
    """
    use this func to filter out the urls to follow only valid urls
    :param: url
    :type: str
    :return: True if the passed url is valid otherwise return false
    :rtype: bool
    """

    #the following regex is copied from Django source code 
    # to validate a url using regax
    
    regex = re.compile(
        r"^(?:http|ftp)s?://"  # http:// or https://
        r"(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|"  # domain...
        r"localhost|"  # localhost...
        r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"  # ...or ip
        r"(?::\d+)?"  # optional port
        r"(?:/?|[/?]\S+)$",
        re.IGNORECASE,
    )


    blocked_sites: list[str] = []

    for site in blocked_sites:
        if site in url or site == url:
            return False

    # if none of the above then ensure that the url is valid and then return True otherwise return False
    if re.match(regex, url):
        return True

    return False
Uri uri = null;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri)
    return false;
else
    return true;

这里url是你要测试的字符串。

返回bool值:

Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute)

作为使用正则表达式的另一种方法,这段代码使用Uri。TryCreate每个OP,但也检查结果,以确保它的Scheme是http或https之一:

bool passed =
  Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult)
    && (uriResult.Scheme == Uri.UriSchemeHttp
      || uriResult.Scheme == Uri.UriSchemeHttps);

试一试:

bool IsValidURL(string URL)
{
    string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
    Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    return Rgx.IsMatch(URL);
}

它会接受这样的URL:

http (s): / / www . example . com http (s): / / stackoverflow操作。com http (s): / / www . example . com/page http (s): / / www . example . com/page ? id = 1&product = 2 http (s): / / www . example . com/page #开始 http (s) / www . example . com: 8080 http (s): / / 127 . 0 0。1 127 . 0 0。1 www.example.com 操作。com