2

I would like to know whether there is any method in C# that takes out all the content of a string until the first number is encountered. Example:

string myString = "USD3,000";
myString = SomeMethod(myString, [someparameters]);
myString -> "3,000"
CiccioMiami
  • 8,028
  • 32
  • 90
  • 151
  • Cheat sheet: http://regexlib.com/CheatSheet.aspx and Quick Regex tester: http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx – James McCormack May 26 '11 at 12:13

4 Answers4

7

Not inbuilt, but you could just use either a regex, or IndexOfAny:

static void Main()
{
    string myString = "USD3,000";
    var match = Regex.Match(myString, @"[0-9].*");
    if(match.Success)
    {
        Console.WriteLine(match.Value);
    }
}

or

static readonly char[] numbers = "0123456789".ToCharArray();
static void Main()
{
    string myString = "USD3,000";
    int i = myString.IndexOfAny(numbers);
    if (i >= 0)
    {
        string s = myString.Substring(i);
        Console.WriteLine(s);
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

I don't think there are any built-in string methods to do that. However you can tweak the code given in the below post and modify it to achieve what you want:

What is the most efficient way in C# to determine if a string starts with a number and then get all following numbers up until the first non-numeric character?

Community
  • 1
  • 1
Mamta D
  • 6,310
  • 3
  • 27
  • 41
0

You can do it with Regular Expressions.

string myString = "USD3,000";
Regex reg = new Regex("[A-Za-z]");
myString = reg.Replace(myString, "");
Matt
  • 349
  • 2
  • 10
0
    string str = "ddd3,000.00ss";

    string stripped = new Regex(@"(\d{1,3},(\d{3},)*\d{3}(\.\d{1,3})?|\d{1,3}(\.\d{3})?).*").Match(str).Value;

    Console.WriteLine(stripped);

Output:

3,000.00ss

Should match decimal and integer number with or without thousand separators and with or without maximum of 3 decimal places.

Marino Šimić
  • 7,318
  • 1
  • 31
  • 61
  • yes and it fails on "b2b_index_3,000.00ss" like the others giving "2b_index_3,000.00ss", I should revise it a bit... unfortunately there is no easy method to avoid that... but probably noone tried this scenario, yet the answer is accepted... – Marino Šimić May 26 '11 at 12:05