0

I have a string with integers in it which are separated by an arbitrary number and kind of symbols, e.g.:

fr365.43//236hu

and want to convert it into a list of the numbers 365, 43 and 236. Is there an easy way to do this?

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142

5 Answers5

2

Using a regular expression you can extract the numbers from the 'dirty' string

var r = new Regex(@"\d+");
var result = r.Matches("fr365.43//236hu");
foreach (Match match in result)
{
    Console.WriteLine(match.Value);
}
// outputs 365 then 43 then 236
samy
  • 14,832
  • 2
  • 54
  • 82
1

Using Regex.Matches and the following pattern:

(\d+)

Then convert to int.

BlackBear
  • 22,411
  • 10
  • 48
  • 86
1
string s ="fr365.43//236hu";
string result = s.Split(s.Where(x=>!char.IsDigit(x))
                 .Select(x=>x).ToArray())
                 .Where(x=>!String.IsNullOrEmpty(x));

The result is an IEnumerable containing the following: 365 43 236

Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
0

You can use Split method, if you have more separators you should include them too:

str.Split('.','/').Select(x => x.All(char.IsDigit))
   .Select(int.Parse)
   .ToList();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

The way to extract integer numbers from the string:

var res = Regex.Split(str, @"\D+").Where(x => x.Length > 0).Select(int.Parse).ToArray();