using System.Collections.Generic;
using System.Text.RegularExpressions;
public static string CleanRut(string rut)
var data = Regex.Replace(rut, "[^0-9K]", "");
return data.StartsWith('K') ? data.Substring(1) + "K" : data;
public static char RutDigitoVerificador(string rutNumerico)
if (!int.TryParse(rutNumerico, out rut))
throw new ArgumentException("El RUT debe ser un número válido.");
for (; rut != 0; rut /= 10)
s = (s + rut % 10 * (9 - m++ % 6)) % 11;
return (char)((s > 0) ? s + 47 : 75);
static void Main(string[] args)
var registros = new List<string> {
"15302989-K REPÚBLICA DE",
"27.333.035 - 6 REPUBLICA DE",
var rutInvalidos = new List<string>();
var rutValidos = new List<string>();
foreach (var str in registros)
var rutSinFormato = CleanRut(str);
if (string.IsNullOrEmpty(rutSinFormato))
if (rutSinFormato.ToUpper().EndsWith('K'))
rutSinFormato = rutSinFormato.ToUpper().Replace("K","");
var digitoVerificador = RutDigitoVerificador(rutSinFormato);
if (digitoVerificador == 'K')
rutValidos.Add($"{rutSinFormato}-{digitoVerificador}");
if (rutSinFormato.Length <= 8)
var digitoVerificador = RutDigitoVerificador(rutSinFormato);
rutValidos.Add($"{rutSinFormato}-{digitoVerificador}");
if (rutSinFormato.Length == 9)
var ultimoDigito = rutSinFormato[rutSinFormato.Length - 1];
var siUltimoDigito = rutSinFormato.Substring(0, rutSinFormato.Length - 1);
var digitoVerificador = RutDigitoVerificador(siUltimoDigito);
if (ultimoDigito == digitoVerificador)
rutValidos.Add($"{siUltimoDigito}-{ultimoDigito}");
if (rutSinFormato.Length > 9)
Console.WriteLine($"Total buenos {rutValidos.Count}");
rutValidos.ForEach(x => Console.WriteLine(x));
Console.WriteLine($"Total Invalidos: {rutInvalidos.Count}");
rutInvalidos.ForEach(x => Console.WriteLine(x));