正则表达式测试字符串是否以 http://或 https://开头 [英] Regex to test if string begins with http:// or https://

查看:705
本文介绍了正则表达式测试字符串是否以 http://或 https://开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个正则表达式来检查字符串的开头,如果它包含 http://https:// 它应该匹配它.

I'm trying to set a regexp which will check the start of a string, and if it contains either http:// or https:// it should match it.

我该怎么做?我正在尝试以下不起作用的方法:

How can I do that? I'm trying the following which isn't working:

^[(http)(https)]://

推荐答案

您对 [] 的使用不正确 -- 注意 [] 表示 字符class 因此只会匹配一个字符.表达式 [(http)(https)] 转换为匹配一个 (, an h, a ttp)s."(重复字符将被忽略.)

Your use of [] is incorrect -- note that [] denotes a character class and will therefore only ever match one character. The expression [(http)(https)] translates to "match a (, an h, a t, a t, a p, a ), or an s." (Duplicate characters are ignored.)

试试这个:

^https?://

如果您真的想使用交替,请改用以下语法:

If you really want to use alternation, use this syntax instead:

^(http|https)://

这篇关于正则表达式测试字符串是否以 http://或 https://开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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