Add extension methods to string class - CSharp Custom Type

CSharp examples for Custom Type:Extension Methods

Description

Add extension methods to string class

Demo Code

using static System.Console;
using System;/*ww  w  .ja  v a  2 s . c o m*/
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
class Program
{
   static void Main(string[] args)
   {
      Write("Enter a valid color value in hex: ");
      string hex = ReadLine();
      WriteLine($"Is {hex} a valid color value: {hex.IsValidHex()}");
      Write("Enter a valid XML tag: ");
      string xmlTag = ReadLine();
      WriteLine($"Is {xmlTag} a valid XML tag: {xmlTag.IsValidXmlTag()}");
      Write("Enter a valid password: ");
      string password = ReadLine();
      WriteLine($"Is {password} a valid password: {password.IsValidPassword()}");
   }
}
public static class StringExtensions
{
   public static bool IsValidXmlTag(this string input)
   {
      return Regex.IsMatch(input, @"^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$");
   }
   public static bool IsValidPassword(this string input)
   {
      // minimum of eight valid characters
      return Regex.IsMatch(input, "^[a-zA-Z0-9_-]{8,}$");
   }
   public static bool IsValidHex(this string input)
   {
      // three or six valid hex number characters
      return Regex.IsMatch(input, "^#?([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$");
   }
}

Result


Related Tutorials