Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 정규식을 사용하여 URL의 유효성을 검사하는 방법은 무엇입니까?

<시간/>

확인하려면 프로토콜을 확인해야 합니다.

http
https

이를 통해 .com, .in, .org 등을 확인해야 합니다.

이를 위해 다음 정규식을 사용하십시오 -

(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?

다음은 코드입니다 -

예시

using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
   class Program {
      private static void showMatch(string text, string expr) {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc) {
            Console.WriteLine(m);
         }
      }
      static void Main(string[] args) {
         string str = "https://example.com";
         Console.WriteLine("Matching URL...");
         showMatch(str, @"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?");
         Console.ReadKey();
      }
   }
}

출력

Matching URL...
The Expression: ^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?
https://example.com