Removing numbers at the end of a C # line

I am trying to remove the numbers at the end of this line.

AB123 -> AB 123ABC79 -> 123ABC 

I tried something like this:

 string input = "123ABC79"; string pattern = @"^\\d+|\\d+$"; string replacement = ""; Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); 

But the replacement string is the same as the input. I am not very familiar with regex. I can just split the string into an array of characters and iterate over it to do this, but that doesn't seem like a good solution. What is good practice to remove numbers that are only at the end of a line?

Thanks in advance.

+5
source share
5 answers

Try the following:

 string input = "123ABC79"; string pattern = @"\d+$"; string replacement = ""; Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); 

Putting $ at the end restricts the search to numeric substrings at the end. Then, since we call Regex.Replace , we need to pass the replacement parameter as the second parameter.

Demo

+10
source

String.TrimEnd () is faster than using a regular expression:

 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 
+16
source

try the following:

 string input = "123ABC79"; string pattern = @".+\D+(?=\d+)"; Match match = Regex.Match(input, pattern); string result = match.Value; 

but you can also use a simple loop:

 string input = "123ABC79"; int i = input.Length - 1; for (; i > 0 && char.IsDigit(input[i - 1]); i--) {} string result = input.Remove(i); 
+2
source
  (? <=[A-Za-z]*)\d* 

Should analyze it

+1
source

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 this from this post: Simple get string (ignore numbers at the end) in C #

+1
source

Source: https://habr.com/ru/post/1208329/


All Articles