Reputation: 826
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.
Upvotes: 19
Views: 26551
Reputation: 131
you can use this:
string strInput = textBox1.Text;
textBox2.Text = strInput.TrimEnd(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
I got it from this post: Simple get string (ignore numbers at end) in C#
Upvotes: 2
Reputation: 1474
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
Upvotes: 46
Reputation: 10015
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);
Upvotes: 2
Reputation: 21757
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.
Upvotes: 16