how to detect strings that end with a number

2019-06-14 13:41发布

i am trying to parse out a string and in some cases there is an extra " - [some number]" at the end. for example,

instead of showing

 Technologist

it shows

Technologist - 23423

i dont want to just check or split on "-" because there are other names that do have a "-" in them

can anyone think of a clean way of removing this extra noise so:

Technologist - 23423 resolves to Technologist

2条回答
乱世女痞
2楼-- · 2019-06-14 14:31

Try this regular expression:

var strRegex = @"\s*-\s*\d+$";

var regex = new Regex(strRegexs);

var strTargetString = "Technologist - 23423";

var res = myRegex.Replace(strTargetString, "");

This will work on the following strings (all is evaluating to Text):

Text - 34234
Text -1
Text    -     342
Text-3443
查看更多
放我归山
3楼-- · 2019-06-14 14:34

This looks like a case regular expressions, such as @" - \d+$" in this case. Sample code:

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

Note that this currently doesn't spot negative numbers. If you wanted it to, you could use

new Regex(@"- -?\d+$");
查看更多
登录 后发表回答