提取数字字符串c#

-5 c# regex serial-port substring extract

我有字符串:

  1. 湿度:33%
  2. 温度:25.7℃
  3. 可见光:112 lx
  4. 红外辐射:1802.5 mW/m2
  5. 紫外线指数:0.12
  6. CO2:404 ppm CO2
  7. 压力:102126 Pa

我必须提取"湿度:"之后的所有数字,...我正在考虑使用Regex类,但我不确切知道如何做到这一点

我获取串行数据的代码:

namespace Demo1Arduino
Run Code Online (Sandbox Code Playgroud)

{

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Dmi*_*nko 5

尝试正则表达式,唯一的技巧是CO2m2 - 我们不希望2这就是我添加的原因\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();
Run Code Online (Sandbox Code Playgroud)

测试

   Console.Write(string.Join("; ", numbers));
Run Code Online (Sandbox Code Playgroud)

结果

   33; 25.7; 112; 1802.5; 0.12; 404; 102126
Run Code Online (Sandbox Code Playgroud)

  • 你之所以选择`[0-9] +`而不是`\ d +`? (2认同)
  • @ThePerplexedOne:C#中的`\ d`包括*全*数字,例如*波斯语*:`0 1 2 3 4 5 6 7 8 9` (2认同)
  • @ThePerplexedOne:简单测试:`if(Regex.IsMatch("0123",@"\ d +"))Console.Write("matched!");`如果你喜欢`\ d`你必须*添加选项*: `.Matches(source,@"\ b\d +(?:\.\ d +)?\ b",RegexOptions.ECMAScript)`请注意`RegexOptions.ECMAScript` (2认同)