• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 493
  • Last Modified:

Extract digit number from a string

Hello, just need an advice.

I have strings, each of them might contain digit number. For example,
string str1 = "abcdet5678sd"; // containg 5678
srting str2 = "dfg34567c"; // containing 2456

Open in new window

I want to extract these numeric values.
Finally we will get
string new_str = "5678"
string new_str = "34567";

Open in new window

The question is that we don't know how long of the digit number and what is the position.
Also it may not have a number in the string, in this case, just give a message.
Thanks for advice.
0
zhshqzyc
Asked:
zhshqzyc
  • 2
  • 2
1 Solution
 
DhaestCommented:
http://www.java2s.com/Code/CSharp/Language-Basics/Useregularexpressiontogetnumberfromstring.htm
using System;
using System.Data;
using System.Text.RegularExpressions;

class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(GetNumberFromStr(IsNum));    // +111
      Console.WriteLine(GetNumberFromStr(IsNotNum));  // 
      Console.WriteLine(GetNumberFromStr(IsFloat));  // 23.11
      Console.WriteLine(GetNumberFromStr(IsExp));    // 
        }
    public static string GetNumberFromStr(string str)
    {
      str = str.Trim();
      Match m = Regex.Match(str, @"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$");
      return (m.Value);
    }
    
}

Open in new window

0
 
zhshqzycAuthor Commented:
Well, the code will get "+111" from "111west". But I only want to get "111".
And if the original string pattern likes "abc111west", I suspect whether it works or not?
     
0
 
DhaestCommented:
Try the following:
string str = "abc111west";
str = string.Join(null, System.Text.RegularExpressions.Regex.Split(str, "[^\\d]"));
0
 
EDDYKTCommented:
how about

public string GetNumberFromStr(string str)
        {
            string ss = "";
            foreach (char s in str)
            {
                int a = 0;
                if (int.TryParse(Convert.ToString(s), out a))
                    ss += a;
            }

            return ss;
        }
0
 
zhshqzycAuthor Commented:
@Dhaest:

Can we remove the chat "^" in the regular expression?
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now