I'm trying to remove numbers in the end of a given string.
AB123 -> AB
123ABC79 -> 123ABC
I've tried something like this;
string input = "123ABC79";
string pattern = @"^\\d+|\\d+$";
string replacement = "";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Yet the replacement string is same as the input. I'm not very familiar with regex. I can simply split the string into a character array, and loop over it to get it done, but it does not feel like a good solution. What is a good practice to remove numbers that are only in the end of a string?
Thanks in advance.
Every string in C ends with '\0'. So you need do this: int size = strlen(my_str); //Total size of string my_str[size-1] = '\0'; This way, you remove the last char.
slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.
String.TrimEnd() is faster than using a regex:
var digits = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
var input = "123ABC79";
var result = input.TrimEnd(digits);
Benchmark app:
string input = "123ABC79";
string pattern = @"\d+$";
string replacement = "";
Regex rgx = new Regex(pattern);
var iterations = 1000000;
var sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
rgx.Replace(input, replacement);
}
sw.Stop();
Console.WriteLine("regex:\t{0}", sw.ElapsedTicks);
var digits = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
sw.Restart();
for (int i = 0; i < iterations; i++)
{
input.TrimEnd(digits);
}
sw.Stop();
Console.WriteLine("trim:\t{0}", sw.ElapsedTicks);
Result:
regex: 40052843
trim: 2000635
Try this:
string input = "123ABC79";
string pattern = @"\d+$";
string replacement = "";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Putting the $ at the end will restrict searches to numeric substrings at the end. Then, since we are calling Regex.Replace, we need to pass in the replacement pattern as the second parameter.
Demo
try this:
string input = "123ABC79";
string pattern = @".+\D+(?=\d+)";
Match match = Regex.Match(input, pattern);
string result = match.Value;
but you also can use a simple cycle:
string input = "123ABC79";
int i = input.Length - 1;
for (; i > 0 && char.IsDigit(input[i - 1]); i--)
{}
string result = input.Remove(i);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With