如何检测以数字结尾的字符串

我试图解析一个字符串,在某些情况下,最后有一个额外的“ – [某个数字]”。 例如,

而不是显示

Technologist 

表明

 Technologist - 23423 

我不想只是检查或拆分“ – ”,因为还有其他名称,其中有“ – ”

任何人都可以想到一个清除方式来消除这些额外的噪音,所以:

技术专家 – 23423解决了技术专家

这看起来像一个正则表达式,例如@“ – \ d + $”。 示例代码:

 using System; using System.Text.RegularExpressions; class Test { static void Main() { Tidy("Technologist - 12345"); Tidy("No trailing stuff"); Tidy("A-B1 - 1 - other things"); } private static readonly Regex regex = new Regex(@"- \d+$"); static void Tidy(string text) { string tidied = regex.Replace(text, ""); Console.WriteLine("'{0}' => '{1}'", text, tidied); } } 

请注意,这目前没有发现负数。 如果你想要它,你可以使用

 new Regex(@"- -?\d+$"); 

试试这个正则表达式:

 var strRegex = @"\s*-\s*\d+$"; var regex = new Regex(strRegexs); var strTargetString = "Technologist - 23423"; var res = myRegex.Replace(strTargetString, ""); 

这将适用于以下字符串(所有字符串都在评估):

 Text - 34234 Text -1 Text - 342 Text-3443