Regex to test if string begins with http:// or https://

后端 未结 9 917
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 06:41

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 c

相关标签:
9条回答
  • 2020-12-04 07:04
    ^https?://
    

    You might have to escape the forward slashes though, depending on context.

    0 讨论(0)
  • 2020-12-04 07:14

    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.)

    Try this:

    ^https?://
    

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

    ^(http|https)://
    
    0 讨论(0)
  • 2020-12-04 07:15

    ^https?:\/\/(.*) where (.*) is match everything else after https://

    0 讨论(0)
  • 2020-12-04 07:15

    (http|https)?:\/\/(\S+)

    This works for me

    Not a regex specialist, but i will try to explain the awnser.

    (http|https) : Parenthesis indicates a capture group, "I" a OR statement.

    \/\/ : "\" allows special characters, such as "/"

    (\S+) : Anything that is not whitespace until the next whitespace

    0 讨论(0)
  • 2020-12-04 07:19

    ^ for start of the string pattern,

    ? for allowing 0 or 1 time repeat. ie., s? s can exist 1 time or no need to exist at all.

    / is a special character in regex so it needs to be escaped by a backslash \/

    /^https?:\/\//.test('https://www.bbc.co.uk/sport/cricket'); // true
    
    /^https?:\/\//.test('http://www.bbc.co.uk/sport/cricket'); // true
    
    /^https?:\/\//.test('ftp://www.bbc.co.uk/sport/cricket'); // false
    
    0 讨论(0)
  • 2020-12-04 07:20

    This should work

    ^(http|https)://
    
    0 讨论(0)
提交回复
热议问题