简体   繁体   English

删除字符串末尾的数字C#

[英]Removing numbers at the end of a string C#

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. 提前致谢。

String.TrimEnd() is faster than using a regex: String.TrimEnd()比使用正则表达式更快:

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. 然后,由于我们调用Regex.Replace ,我们需要将替换模式作为第二个参数传递。

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);

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# 我从这篇文章中得到了它: 在C#中简单获取字符串(忽略数字)

 (? <=[A-Za-z]*)\d*

应该解析它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM