You can use the expression \d+$
, it tries to find any digits that are at the end of string .
Constructing a Regex
instance with this expression, you can validate the substring size that was found and then do the replacement if this string that was found has more than 4 characters .
See an example:
using static System.Console;
using System.Text.RegularExpressions;
public class Program
{
public static string Remover4DigitosFinais(string input)
{
var expressao = new Regex(@"\d+$");
var r = expressao.Match(input);
return r.Length > 4 ? expressao.Replace(input, "").TrimEnd() : input;
}
public static void Main()
{
var validacoes = new []
{
new { Input = "MARIA 2 APARECIDA DE SOUZA MOURA 636598241", Esperado = "MARIA 2 APARECIDA DE SOUZA MOURA" },
new { Input = "MARIA 2 APARECIDA DE SOUZA MOURA 2018", Esperado = "MARIA 2 APARECIDA DE SOUZA MOURA 2018" },
new { Input = "JOAO 175", Esperado = "JOAO 175" },
new { Input = "JOAO 1751233", Esperado = "JOAO" },
};
foreach(var val in validacoes)
{
var novo = Remover4DigitosFinais(val.Input);
var sucesso = (novo == val.Esperado);
WriteLine($"Sucesso: {sucesso} - Entrada: {val.Input} - Saída: {novo} - Esperado: {val.Esperado}");
}
}
}
See working in .NET Fiddle.
This is sure to be great if you want to take responsibility for regex and therefore have a shorter and easier to understand expression.
Otherwise, you can simply use the expression (\s\d{5,})+$
, it tries to find any substring where the first character is a space ( \s
), after this space% of digits ( \d
), which are at the end of the main string ( $
) as long as this combination has size greater than five ( {5,}
).
public static string Remover4DigitosFinais(string input)
{
var expressao = new Regex(@"(\s\d{5,})+$");
return expressao.Replace(input, "");
}
See working in .NET Fiddle.