Skip to content

Instantly share code, notes, and snippets.

@pfrozi
Created June 23, 2021 17:44
Show Gist options
  • Save pfrozi/afcfe51be5f4e761f9a2c86bae8b5beb to your computer and use it in GitHub Desktop.
Save pfrozi/afcfe51be5f4e761f9a2c86bae8b5beb to your computer and use it in GitHub Desktop.
Regex to test repeated character in C#
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var hasRepeatedCharacter = new Regex(@"^([0-9]+)\1$");
string text = "123123";
Console.WriteLine($"Valid {text}: {hasRepeatedCharacter.IsMatch(text)}");
text = "1233321";
Console.WriteLine($"Valid {text}: {hasRepeatedCharacter.IsMatch(text)}");
text = "3311";
Console.WriteLine($"Valid {text}: {hasRepeatedCharacter.IsMatch(text)}");
Console.WriteLine("Testing other regex:");
hasRepeatedCharacter = new Regex(@"^([0-9]*)([0-9]+)\2([0-9]*)$");
Console.WriteLine($"Valid {text}: {hasRepeatedCharacter.IsMatch(text)}");
text = "31313100";
Console.WriteLine($"Valid {text}: {hasRepeatedCharacter.IsMatch(text)}");
text = "00313131";
Console.WriteLine($"Valid {text}: {hasRepeatedCharacter.IsMatch(text)}");
text = "11";
Console.WriteLine($"Valid {text}: {hasRepeatedCharacter.IsMatch(text)}");
text = "123456";
Console.WriteLine($"Valid {text}: {hasRepeatedCharacter.IsMatch(text)}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment