我随机地从串口读取代码,我希望在特定位置获取特定数据,但是端口连续发送数据,就像那样
H91F O69F S124F D-1F H94F O70F S119F D-2F H95F O69F S119F D0F H90F O70F S122F D2F H91F O69F S123F D3F H93F O69F S122F D5F H94F O71F S122F D2F H92F O69F S120F D1F H92F O69F S121F D1F H91F O69F S122F D1F H91F O70F S120F D-2F H95F O73F S121F D-4F H90F O69F S124F D-2F H94F O72F S123F D-3F H90F O70F S119F D-5F H94F O72F S122F D-6F H95F O69F S122F D-9F H90F O69F S123F D-11F
从H
到最后F
H91F O69F S124F D-1F
然后另一行H94F O70F S119F D-2F
我需要获取每个字母之间的数字,例如H
和F
之间以及O
和F
之间的数字
SerialPort serialPort = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
serialPort.Open();
string datasize = serialPort.ReadTo("D");
string firstdata = "";
firstdata = serialPort.ReadExisting();
string data = "";
int firsth = 0;
int firstd = 0;
int lastf = 0;
firsth = firstdata.IndexOf("H");
firstd = firstdata.IndexOf("D" , startIndex: firsth);
lastf = firstdata.IndexOf("F" , startIndex: firstd);
data = firstdata.Substring(firsth, lastf + 1);
// MessageBox.Show(data);
int h = data.IndexOf("H");
int firstF = data.IndexOf("F" , startIndex: h);
string hdata = data.Substring(h + 1, firstF - h - 1);
// string hstring = Regex.Match(hdata, @"\d+").Value;
PulseBox.Text = hdata;
int o = data.IndexOf("O");
int secondF = data.IndexOf("F", startIndex: o);
string odata = data.Substring(o + 1, secondF - o - 1);
// string ostring = Regex.Match(odata, @"\d+").Value;
OxyBox.Text = odata;
int s = data.IndexOf("S");
int thirdF = data.IndexOf("F" , startIndex: s);
string sdata = data.Substring(s + 1, thirdF - s - 1);
// string sstring = Regex.Match(sdata, @"\d+").Value;
SystolicPressure.Text = sdata;
int d = data.IndexOf("D");
int fourthF = data.IndexOf("F", startIndex: d);
string ddata = data.Substring(d + 1, fourthF - d - 1);
// string dstring = Regex.Match(data, @"\d+").Value;
DiastolicPressure.Text = ddata;
答案 0 :(得分:1)
在处理固定模式时,应使用正则表达式(请参阅https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference以获取对正则表达式的引用)。在你的情况下,这将是:
var regex = new Regex(@"H(?<H>[\-\d]+)F O(?<O>[\-\d]+)F S(?<S>[\-\d]+)F D(?<D>[\-\d]+)F");
var input = serialPort.ReadExisting(); // e.g. "H91F O69F S124F D-1F H94F O70F S119F D-2F H95F O69F S119F D0F H90F O70F S122F D2F H91F O69F S123F D3F H93F O69F S122F D5F H94F O71F S122F D2F H92F O69F S120F D1F H92F O69F S121F D1F H91F O69F S122F D1F H91F O70F S120F D-2F H95F O73F S121F D-4F H90F O69F S124F D-2F H94F O72F S123F D-3F H90F O70F S119F D-5F H94F O72F S122F D-6F H95F O69F S122F D-9F H90F O69F S123F D-11F";
如果您将此正则表达式应用于输入,它将返回所有匹配项:
var matches = regex.Matches(input);
foreach (Match match in matches)
{
// match.Value will be your complete match, e.g. "H91F O69F S124F D-1F"
// match.Groups["H"].Value will contain the value for H, e.g. "91"
// match.Groups["O"].Value will contain the value for O, e.g. "69"
// match.Groups["S"].Value will contain the value for S, e.g. "124"
// match.Groups["D"].Value will contain the value for D, e.g. "-1"
}