简体   繁体   中英

How to extract numbers from a string which is not in same format?

I have a string like below:

string str = "data:clientId:12345::processId::23";

I want to extract two numbers in the above string. It is not in the same format otherwise I would have split on one delimiters and get those two numbers out of it. How can I parse abvoe string and get those two numbers out of it?

string[] tokens = str.Split(':');

A simple one line LINQ solution checks for numbers and empty strings:

string str = "data:clientId:12345::processId::23";
var tokens = str.Split(':').Where(t => t.All(char.IsDigit) && string.IsNullOrWhiteSpace(t) == false);

It does not matter you have : and ::

    string str = "data:clientId:12345::processId::23";
    
    string[] items = str.Split(':');
    
    Console.WriteLine(items[2]);
    Console.WriteLine(items[6]);

Output:

12345
23

I really don't see the problem to this question, unless there is something not mentioned or something big I'm missing. If you split by ':', then the parts delimited with '::' will be returned as an empty string.

So you just need to try to parse each part as an integer, if it works, then it is part of the solution.

    static int[] ExtractNumbers(string s)
    {
        var toret = new List<int>();
        string[] parts = s.Split( ":" );
        
        foreach(string part in parts) {
            if ( int.TryParse( part, out int x ) )
            {
                toret.Add( x );
            }
        }
        
        return toret.ToArray();
    }

An easy way you could go about to extract numbers from strings is through regular expressions as you can see from the following link to another question asking what's the regex to match numbers:

Regular expression to extract numbers from a string

As the code to extract it you may go with something like this:

string inputStr = "data:clientId:12345::processId::23";
string regexPattern = @"\d+";
MatchCollection matches = Regex.Matches(inputStr , regexPattern);
foreach (Match m in matches)
  Console.WriteLine("{0} at index {1}", m.Value, m.Index);

Like this you should be able to see your numbers contained in the string, from there you can get the numbers in the forach like

int numberVal = Convert.ToInt32(m.Value);

One for each match (there should be two in your input)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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