Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific numbers from string

Tags:

string

c#

split

In my current project I have to work alot with substring and I'm wondering if there is an easier way to get out numbers from a string.

Example: I have a string like this: 12 text text 7 text

I want to be available to get out first number set or second number set. So if I ask for number set 1 I will get 12 in return and if I ask for number set 2 I will get 7 in return.

Thanks!

like image 892
Tobias Lindberg Avatar asked May 05 '12 18:05

Tobias Lindberg


People also ask

How do I extract numbers from a string in Excel?

Extract Numbers from String in Excel (using VBA) Since we have done all the heavy lifting in the code itself, all you need to do is use the formula =GetNumeric(A2). This will instantly give you only the numeric part of the string.

How do I extract specific numbers from a cell in Excel?

2. Extracting Numbers from the Right of a Text or Number String by Combining RIGHT, LEN, MIN & SEARCH Functions. Press Enter & then use Fill Handle to autofill the rest of the cells. MIN function is used to find the lowest digit or number from an array.


3 Answers

This will create an array of integers from the string:

using System.Linq;
using System.Text.RegularExpressions;

class Program {
    static void Main() {
        string text = "12 text text 7 text";
        int[] numbers = (from Match m in Regex.Matches(text, @"\d+") select int.Parse(m.Value)).ToArray();
    }
}
like image 120
Paolo Tedesco Avatar answered Sep 23 '22 19:09

Paolo Tedesco


Try using regular expressions, you can match [0-9]+ which will match any run of numerals within your string. The C# code to use this regex is roughly as follows:

Match match = Regex.Match(input, "[0-9]+", RegexOptions.IgnoreCase);

// Here we check the Match instance.
if (match.Success)
{
    // here you get the first match
    string value = match.Groups[1].Value;
}

You will of course still have to parse the returned strings.

like image 36
ColinE Avatar answered Sep 23 '22 19:09

ColinE


Looks like a good match for Regex.

The basic regular expression would be \d+ to match on (one or more digits).

You would iterate through the Matches collection returned from Regex.Matches and parse each returned match in turn.

var matches = Regex.Matches(input, "\d+");

foreach(var match in matches)
{
    myIntList.Add(int.Parse(match.Value));
}
like image 24
Oded Avatar answered Sep 24 '22 19:09

Oded