我希望能够检查一个字符串,看它是否以http://开头,如果不是,则添加。
if (regex expression){
string = "http://"+string;
}
有人知道要使用哪个正则表达式吗?
如果你不需要使用正则表达式来处理这个问题(取决于你使用的编程语言),你可以直接查看字符串的前面几个字符。例如:
// C#
if (!str.StartsWith("http://"))
str = "http://" + str;
// Java
if (!str.startsWith("http://"))
str = "http://" + str;
// JavaScript/TypeScript
if (str.substring(0, 7) !== 'http://')
str = 'http://' + str;
应该是:
/^http:\/\//
请记得在使用时加上 !
或 not
(你没有说明使用哪种编程语言),因为你正在寻找不匹配的项目。
在JavaScript中:
if(!(/^http:\/\//.test(url)))
{
string = "http://" + string;
}
var url = "http://abcd";
var pattern = /^((http|https|ftp):\/\/)/;
if(!pattern.test(url)) {
url = "http://" + url;
}
alert(url);
类似这样的应该可以工作:^(https?://)
yourString = yourString.StartWith("http://") ? yourString : "http://" + yourString
更加性感
/^http:\/\//
对我来说,使用PHP时这是我使用的两个,为了完整性而添加在此处。
$__regex_url_no_http = "@[-a-zA-Z0-9\@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()\@:%_\+.~#?&//=]*)@";
$__regex_url_http = "@https?:\/\/(www\.)?[-a-zA-Z0-9\@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()\@:%_\+.~#?&//=]*)@";
/**
* Filters a url @param url If @param protocol is true
* then it will check if the url contains the protocol
* portion in the url if it doesn't then false will be
* returned.
*
* @param string $url
* @param boolean $protocol
* @return boolean
*/
public function filter_url($url, $protocol=false){
$response = FALSE;
$regex = $protocol == false ? $this->__regex_url_no_http:$this->__regex_url_http;
if(preg_match($regex, $url)){
$response = TRUE;
}
return $response;
}
我没有创建这个正则表达式。我在某个地方找到了它们,但似乎是符合要求的。