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

后端 未结 9 918
没有蜡笔的小新
没有蜡笔的小新 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:22

    Making this case insensitive wasn't working in asp.net so I just specified each of the letters.

    Here's what I had to do to get it working in an asp.net RegularExpressionValidator:

    [Hh][Tt][Tt][Pp][Ss]?://(.*)
    

    Notes:

    • (?i) and using /whatever/i didn't work probably because javascript hasn't brought in all case sensitive functionality
    • Originally had ^ at beginning but it didn't matter, but the (.*) did (Expression didn't work without (.*) but did work without ^)
    • Didn't need to escape the // though might be a good idea.

    Here's the full RegularExpressionValidator if you need it:

    <asp:RegularExpressionValidator ID="revURLHeaderEdit" runat="server" 
        ControlToValidate="txtURLHeaderEdit" 
        ValidationExpression="[Hh][Tt][Tt][Pp][Ss]?://(.*)"
        ErrorMessage="URL should begin with http:// or https://" >
    </asp:RegularExpressionValidator>
    
    0 讨论(0)
  • 2020-12-04 07:24

    Case insensitive:

    var re = new RegExp("^(http|https)://", "i");
    var str = "My String";
    var match = re.test(str);
    
    0 讨论(0)
  • 2020-12-04 07:24

    This will work for URL encoded strings too.

    ^(https?)(:\/\/|(\%3A%2F%2F))
    
    0 讨论(0)
提交回复
热议问题