如何检查一个字符串是否以http://开头

6

我希望能够检查一个字符串,看它是否以http://开头,如果不是,则添加。

if (regex expression){
string = "http://"+string;
}

有人知道要使用哪个正则表达式吗?

9个回答

58

如果你不需要使用正则表达式来处理这个问题(取决于你使用的编程语言),你可以直接查看字符串的前面几个字符。例如:

// 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;

4
愿你得到许多赞。有时,正则表达式可能过于复杂。 - Samir Talwar
1
谢谢祝福。是的,有时候强大的语言特性被过度使用。正则表达式不如简单的字符串操作快。 - David R Tribble
@Ra91 - 我添加了一个JavaScript示例,它在IE中可以正常工作。 - David R Tribble

8

应该是:

/^http:\/\//

请记得在使用时加上 !not (你没有说明使用哪种编程语言),因为你正在寻找不匹配的项目。


7

在JavaScript中:

if(!(/^http:\/\//.test(url)))
{
    string = "http://" + string;
}

6
var url = "http://abcd";
var pattern = /^((http|https|ftp):\/\/)/;

if(!pattern.test(url)) {
    url = "http://" + url;
}

alert(url);

1
虽然这段代码可能回答了问题,但提供关于它如何以及为什么解决问题的额外上下文会提高答案的长期价值。- 来自审查 - Michael Parker
非常感谢!这有助于我在处理方面的提高。 - Blue Tram

3

类似这样的应该可以工作:^(https?://)


2
yourString = yourString.StartWith("http://") ? yourString : "http://" + yourString

更加性感


1
 /^http:\/\//

0

对我来说,使用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;
}

我没有创建这个正则表达式。我在某个地方找到了它们,但似乎是符合要求的。


0
如果需要使用 JavaScript 这种语言,请查看这篇文章,它会将“startswith”属性添加到字符串类型中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接