URL的正则表达式
我写了正则表达式来validationURL,可能就像
所有4个都在工作
现在,如果我输入的文本(www.example.com – thisisincorrect),它允许我输入并保存到db
我使用的正则表达式是:
http(s)?://([w-]+.)+[w-]+(/[w- ./?%&=]*)?
和
([w-]+.)+[w-]+(/[w- ./?%&=]*)?
请帮忙!
添加^
和$
^http(s)?://([w-]+.)+[w-]+(/[w- ./?%&=])?$
这匹配字符串( ^
)和结束( $
)的开头
您不需要URL的正则表达式,请使用System.Uri
类。 例如,通过使用Uri.IsWellFormedUriString
方法:
bool isUri = Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute);
最佳正则表达式:
private bool IsUrlValid(string url) { string pattern = @"^(http|https|ftp|)://|[a-zA-Z0-9-.]+.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9-._?,'/\+&%$#=~])*[^.,)(s]$"; Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); return reg.IsMatch(url); }
在为严格匹配创建正则表达式时,必须确保它以’^’开头并以’$’结束。 否则,正则表达式将查看它是否找到匹配的子字符串。
但是,使用正则表达式来匹配URL是容易出错的:更好地依赖现有框架做得更好(url中有很多潜在的陷阱,比如参数,未知域,包含ip而不是域的URL ….)
你正在寻找这个
没有Http:
@"^(www.|[a-zA-Z].)[a-zA-Z0-9-.]+.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(:[0-9]+)*(/($|[a-zA-Z0-9.,;?'\+&%$#=~_-]+))*$"
使用Http:s:
@"^(((ht|f)tp(s?))://)?(www.|[a-zA-Z].)[a-zA-Z0-9-.]+.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(:[0-9]+)*(/($|[a-zA-Z0-9.,;?'\+&%$#=~_-]+))*$"
要么
@"^[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/S*)?$";
这对我有用:
string pattern = @"^(ht|f)tp(s?)://[0-9a-zA-Z]([-.w]*[0-9a-zA-Z])*(:(0-9)*)*(/?)([a-zA-Z0-9-.?,'/\+&%$#_]*)?$"; Regex regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); string url= txtAddressBar.Text.Trim(); if(regex.IsMatch(url) { //do something }
这是为了支持http,https作为可选,并且validation空白空间不包含在url中。
上述就是C#学习教程:URL的正则表达式分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
this.isValidURL = function (url) { if (!url) return false; const expression = /^(?:http(s)?://)?[w.-]+(?:.[w.-]+)+[w-._~:/?#[]@!$&'()*+,;=.]+$/gm; return url.match(new RegExp(expression)); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/955395.html