我有字符串:
我必须提取“湿度:'之后的所有数字”。 ,.. 我当时正在考虑使用Regex类,但我不知道该怎么做
我获取串行数据的代码:
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();
}
}
谢谢
答案 0 :(得分:1)
在不知道类型的情况下获取多个数字是没有意义的。我将值放入字典中,以便在代码中稍后使用该数字。请参阅下面的代码和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();
}
}
}