-5 c# regex serial-port substring extract
我有字符串:
我必须提取"湿度:"之后的所有数字,...我正在考虑使用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)
谢谢
尝试正则表达式,唯一的技巧是CO2和m2 - 我们不希望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)