extract number out strings c# [closed]

Try regular expression, the only trick is CO2 and m2 – we don’t want 2 that’s why I’ve added \b:

  string source =
    @"Humidity: 33 %
      Temperature: 25.7 deg C
      Visible light: 112 lx
      Infrared radiation: 1802.5 mW/m2
      UV index: 0.12
      CO2: 404 ppm CO2
      Pressure: 102126 Pa";

  string[] numbers = Regex
      .Matches(source, @"\b[0-9]+(?:\.[0-9]+)?\b")
      .OfType<Match>()
      .Select(match => match.Value)
      .ToArray();

Test

   Console.Write(string.Join("; ", numbers));

Outcome

   33; 25.7; 112; 1802.5; 0.12; 404; 102126

Leave a Comment