Get specific numbers from a string

In my current project, I have to work a lot with substring, and I wonder if there is an easier way to output numbers from a string.

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

I want to be available to exit the first set of numbers or the second number. Therefore, if I ask to set number 1, I will get 12 in return, and if I ask to set number 2, I will return 7.

Thank!

+5
source share
5 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();
    }
}
+7
source

Looks like a good match Regex.

The main regular expression will be \d+for matching (one or more digits).

Matches, Regex.Matches, .

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

foreach(var match in matches)
{
    myIntList.Add(int.Parse(match.Value));
}
+1

Try using regular expressions, you can match [0-9]+, which will match any run of numbers in your string. C # code to use this regex looks something like this:

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

Of course, you still have to parse the returned strings.

+1
source

You can use regex:

Regex regex = new Regex(@"^[0-9]+$");
0
source

you can split the string in parts with string.Split and then move the list with foreach using int.TryParse, something like this:

string test = "12 text text 7 text";
var numbers = new List<int>();
int i;
foreach (string s in test.Split(' '))
{
     if (int.TryParse(s, out i)) numbers.Add(i);
}

Numbers now have a list of valid values

0
source

All Articles