C# program to check for URL in a String

In C#, you can check for URLs in a string using various methods such as StartsWith() for simple prefix matching or regular expressions for more comprehensive URL validation. The StartsWith() method is useful when you need to verify if a string begins with a specific URL pattern.

Syntax

Following is the syntax for using StartsWith() to check URL prefixes −

string.StartsWith("url_prefix")

For checking multiple URL patterns, you can combine conditions using logical operators −

if (input.StartsWith("https://www.") || input.StartsWith("https://")) {
   // URL found
}

Using StartsWith() for Simple URL Detection

The StartsWith() method checks if a string begins with a specified substring. This approach works well when you know the exact URL patterns to look for −

using System;

class Demo {
   static void Main() {
      string input = "https://example.com/new.html";
      
      // Check if input matches specific URL patterns
      if (input.StartsWith("https://www.example.com") || input.StartsWith("https://example.com")) {
         Console.WriteLine("URL found: " + input);
         Console.WriteLine("Result: True");
      } else {
         Console.WriteLine("No matching URL found");
         Console.WriteLine("Result: False");
      }
   }
}

The output of the above code is −

URL found: https://example.com/new.html
Result: True

Using Regular Expressions for Comprehensive URL Validation

For more robust URL detection that can identify various URL formats, regular expressions provide a better solution −

using System;
using System.Text.RegularExpressions;

class URLChecker {
   static void Main() {
      string[] testStrings = {
         "Visit https://www.example.com for more info",
         "Check out http://test.org/page.html",
         "ftp://files.example.com/download",
         "This is just plain text",
         "https://subdomain.example.co.uk/path?query=value"
      };
      
      string urlPattern = @"https?://[^\s]+|ftp://[^\s]+";
      
      foreach (string text in testStrings) {
         Match match = Regex.Match(text, urlPattern);
         if (match.Success) {
            Console.WriteLine("Text: " + text);
            Console.WriteLine("URL found: " + match.Value);
            Console.WriteLine("---");
         } else {
            Console.WriteLine("Text: " + text);
            Console.WriteLine("No URL found");
            Console.WriteLine("---");
         }
      }
   }
}

The output of the above code is −

Text: Visit https://www.example.com for more info
URL found: https://www.example.com
---
Text: Check out http://test.org/page.html
URL found: http://test.org/page.html
---
Text: ftp://files.example.com/download
URL found: ftp://files.example.com/download
---
Text: This is just plain text
No URL found
---
Text: https://subdomain.example.co.uk/path?query=value
URL found: https://subdomain.example.co.uk/path?query=value
---

Using Uri.TryCreate() for URL Validation

The Uri.TryCreate() method provides a built-in way to validate if a string represents a valid URI −

using System;

class URIValidator {
   static void Main() {
      string[] urls = {
         "https://www.example.com",
         "http://invalid-url",
         "ftp://files.server.com/file.zip",
         "not-a-url",
         "https://google.com/search?q=csharp"
      };
      
      foreach (string url in urls) {
         Uri validUri;
         bool isValid = Uri.TryCreate(url, UriKind.Absolute, out validUri);
         
         Console.WriteLine("URL: " + url);
         Console.WriteLine("Valid: " + isValid);
         if (isValid) {
            Console.WriteLine("Scheme: " + validUri.Scheme);
            Console.WriteLine("Host: " + validUri.Host);
         }
         Console.WriteLine("---");
      }
   }
}

The output of the above code is −

URL: https://www.example.com
Valid: True
Scheme: https
Host: www.example.com
---
URL: http://invalid-url
Valid: True
Scheme: http
Host: invalid-url
---
URL: ftp://files.server.com/file.zip
Valid: True
Scheme: ftp
Host: files.server.com
---
URL: not-a-url
Valid: False
---
URL: https://google.com/search?q=csharp
Valid: True
Scheme: https
Host: google.com
---

Comparison of URL Detection Methods

Method Use Case Pros Cons
StartsWith() Specific URL prefix matching Simple and fast Limited flexibility
Regular Expressions Pattern-based URL detection Flexible pattern matching More complex, slower
Uri.TryCreate() URI format validation Built-in validation, provides URI components May accept invalid web URLs

Conclusion

For simple URL prefix checking, use StartsWith(). For comprehensive URL detection in text, use regular expressions. For validating URI format and extracting components, Uri.TryCreate() is the most appropriate choice. Choose the method that best fits your specific requirements.

Updated on: 2026-03-17T07:04:35+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements