-6

I Have the string :

  1. Humidity: 33 %
  2. Temperature: 25.7 deg C
  3. Visible light: 112 lx
  4. Infrared radiation: 1802.5 mW/m2
  5. UV index: 0.12
  6. CO2: 404 ppm CO2
  7. Pressure: 102126 Pa

I have to extract all the numbers coming after 'Humidity:' , .. I was thinking to use the Regex class but i dont know exactly how to do it

My code for getting the serial data :

namespace Demo1Arduino

{

public partial class MainWindow : Window
{
    private SerialPort port;
    DispatcherTimer timer = new DispatcherTimer();
    private string buff; 

    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnOpenPort_Click(object sender, RoutedEventArgs e)
    {
        timer.Tick += timer_Tick;          
        timer.Interval = new TimeSpan(0, 0, 0, 0, 500);           
        timer.Start();

        try
        {
            port = new SerialPort();                     // Create a new SerialPort object with default settings.
            port.PortName="COM4";
            port.BaudRate = 115200;                        //  Opent de seriele poort, zet data snelheid op 9600 bps.
            port.StopBits = StopBits.One;                // One Stop bit is used. Stop bits separate each unit of data on an asynchronous serial connection. They are also sent continuously when no data is available for transmission.
            port.Parity = Parity.None;                   // No parity check occurs. 
            port.DataReceived += Port_DataReceived;                                                                                   
            port.Open();                                 // Opens a new serial port connection.
            buff = ""; 
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message); 
        }
    }
    private void timer_Tick(object sender, EventArgs e)
    {
       try
        {
            if(buff != "") 
            {
                textBox.Text += buff;
                buff = ""; 
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message); 
        }
    }

    private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        byte[] buffer = new byte[128];
        int len = port.Read(buffer, 0, buffer.Length); // .Read --> Reads a number of characters from the SerialPort input buffer and writes them into an array of characters at a given offset.

        if(len>0)
        {
            string str = ""; 
            for (int i=0; i<len; i++)
            {
                if (buffer[i] != 0)
                {
                    str = str + ((char)buffer[i]).ToString();
                }
            }
            buff += str; 
        } 
       // throw new NotImplementedException();
    }
}

Thank you

  • 2
    Why would you use a regex for this? `String.Split(':');`. https://dotnetfiddle.net/OpX8Nq . Also none of the code you provided is relevant to what you're trying to do... – sab669 May 11 '17 at 15:17
  • 1
    Your question is basically - "how do i get numbers from a string"? The rest of your code is irrelevant. I don't see enough research into how you can solve this. SO is not a "I want this. How do I do it?" service. You will need to provide details of an issue you might be having and what you have tried to fix it. I would suggest you look at http://stackoverflow.com/questions/4734116/find-and-extract-a-number-from-a-string as a starting point... – Geoff James May 11 '17 at 15:17
  • And what is your question? All I see is "this is the task" and "this is my code". Here on SO we ask specific questions, that is we provide some code and the desired output and what we get instead of this. – MakePeaceGreatAgain May 11 '17 at 15:18

2 Answers2

5

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
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

It makes no sense to get multiple number without know the type. I put values into a dictionary to make it easy to use the number later in the code. See code below and https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication55
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] inputs = {
                "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 pattern = @"^(?'name'[^:]+):\s(?'value'[\d.]+)";

            Dictionary<string, decimal> dict = new Dictionary<string,decimal>();
            foreach(string input in inputs)
            {
                Match match = Regex.Match(input,pattern);
                string name = match.Groups["name"].Value;
                decimal value = decimal.Parse(match.Groups["value"].Value);

                Console.WriteLine("name = '{0}', value = '{1}'", name, value);
                dict.Add(name, value);
            }
            Console.ReadLine();
        }
    }

}
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • Technically, is it make sense or not to get multiple number without knowing the type *depends on the format*: if we guaranteed that first value is humidity, second is temperature etc. we can do without names. However, in general case, names are requiered. +1. Further generalization adds *domain* - deg C, %, Pa etc. – Dmitry Bychenko May 11 '17 at 15:40
  • I wouldn't hire anybody who thinks like that. – jdweng May 11 '17 at 16:16