-3

I got a task for URL validation in which url should not contain any special characters and it should accept only https. I tried with

^((https)://)?([\w+?\.\w+])+([a-zA-Z0-9\\\/\.\:]*)?$

this regex pattern it works fine for special characters but not working for https, Its accepting http also whereas i need it to accept only https. I googled it but unable to find any solution.

Poul Bak
  • 7,390
  • 4
  • 20
  • 40
Zia Zee
  • 17
  • 6
  • 1
    That's because this part: `((https)://)?`means that it is optional. – Poul Bak Apr 15 '21 at 13:25
  • Does this answer your question? [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – Poul Bak Apr 15 '21 at 13:26

2 Answers2

0

You could do something like this for example:

static void Main(string[] args)
{
    string pattern = @"^(https:\/\/)[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
    Regex reg = new Regex(pattern);
    string[] urls = { "https://test.com", "http://test.com" };

    foreach (var item in urls)
    {
        var test = reg.IsMatch(item);
        Console.WriteLine(test.ToString());
    }

    Console.ReadKey();
}

Result is:

True
False
Adlorem
  • 1,050
  • 1
  • 8
  • 9
0

Is regex actually a requirement ?

Actually, it's far more simple (and I guess, efficient) to test for the first 7 characters :

    var tests = new String[]{
        "http://shouldfail",
        "https://shouldsucceed",
        "ftp://fail"
    };
    
    foreach(var test in tests){
        if(test.StartsWith("https://", StringComparison.CurrentCultureIgnoreCase)){
            Console.WriteLine(test + " is OK");
        }else{
            Console.WriteLine(test + " is not OK");
        }
    }
Steve B
  • 34,941
  • 18
  • 92
  • 155