You can use the expression \d+$
, she tries to find any digits that are at the end of string.
Building an instance of Regex
with this expression, you can validate the size of the substring which was found and then replace if this string was found has more than 4 characters.
Take 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 on . NET Fiddle.
This is certainly great if you want to take the responsibility of regex and consequently have a shorter and easier to understand expression.
Otherwise, you can simply use the expression (\s\d{5,})+$
, she tries to find any substring where the first character is a space (\s
), after this space there are digits (\d
), which are at the end of string leading ($
) as long as this combination is larger than five ({5,}
).
public static string Remover4DigitosFinais(string input)
{
var expressao = new Regex(@"(\s\d{5,})+$");
return expressao.Replace(input, "");
}
See working on . NET Fiddle.