从复杂的串行数据中解析唯一字符串
本文关键字:唯一 字符串 数据 复杂 | 更新日期: 2023-09-27 17:49:45
我需要从serial中解析这个字符串:-
!00037,00055@
00037作为一个字符串,00055作为另一个字符串
然而,这个字符串是在机器人的轮胎旋转时出现的,并且在我需要解析的字符串之前和之后也可能显示其他字符串。例如,这是接收到的一些传输:-
11,00085@R-STOPR-STOP!00011,00095@!00001,00015@R-STOP!00001,00085@!00003,00075@!00006,00015@R-STOP!00009,00025@!00011,00035@!00011,00085@R-STOPR-STOP!00011,00095@!00001,00015@R-STOP!00001,00085@!00003,00075@!00006,00015@R-STOP!00009,00025@!00011,00035@R-STOP!00001,00085@!00003,00075@!00006,00015@R-STOP!00009,00025@!00011,00035@R-STOP!00037,00055@!00023,00075@R-STOPR-STOP!00022,00065@!00011,00085@R-STOPR-STOP!00011,00095@!00001,00015@R-STOP!00001,00085@!00003,00075@!00006,00015@R-STOP!00009,00025@!00011,00035@R-STOP!00037,00055@!00023,00075@R-STOPR-STOP!00022,00065@!00011,00085@R-STOPR-STOP!00011,00095@!00001,00015@
到目前为止,我被困在serialport . readeexisting()之后该做什么
下面是一些获取串行数据的代码:-
private void serialCom_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
InputData = serialCom.ReadExisting();
if (InputData != String.Empty)
{
this.BeginInvoke(new SetTextCallback(IncomingData), new object[] { InputData });
}
}
catch
{
MessageBox.Show("Error");
}
}
并在文本框
中显示传入的串行数据private void IncomingData(string data)
{
tb_incomingData.AppendText(data);
tb_incomingData.ScrollToCaret();
}
此代码使用。net Framework 4.0和Windows Form。
最后用indexof和substring求解。
private void IncomingData(string data)
{
//Show received data in textbox
tb_incomingData.AppendText(data);
tb_incomingData.ScrollToCaret();
//Append data inside longdata (string)
longData = longData + data;
if (longData.Contains('@') && longData.Contains(',') && longData.Contains('!'))
{
try
{
indexSeru = longData.IndexOf('!'); //retrieve index number of the symbol !
indexComma = longData.IndexOf(','); //retrieve index number of the symbol ,
indexAlias = longData.IndexOf('@'); //retrieve index number of the symbol ,
rotation = longData.Substring(indexSeru + 1, 5); //first string is taken after symbol ! and 5 next char
subRotation = longData.Substring(indexComma + 1, 5); //second string is taken after symbol ! and 5 next char
//tss_distance.Text = rotation + "," + subRotation;
longData = null; //clear longdata string
}
catch
{
indexSeru = 0;
indexComma = 0;
indexAlias = 0;
}
}
}
您可以使用SPLIT函数确定将此字符串转换为数组的模式。
此代码,发送"!"00037,00055@"返回两个项目:00037和00055。
static void Main(string[] args)
{
string k = "!00037,00055@";
var array = k.ToString().Split(',');
Console.WriteLine("Dirty Itens");
for (var x = 0; x <= array.Length - 1; x++)
{
var linha = "Item " + x.ToString() + " = " + array[x];
Console.WriteLine(linha);
}
Console.WriteLine("Cleaned Itens");
for (var x = 0; x <= array.Length - 1; x++)
{
var linha = "Item " + x.ToString() + " = " + CleanString(array[x]);
Console.WriteLine(linha);
}
Console.ReadLine();
}
public static string CleanString(string inputString)
{
string resultString = "";
Regex regexObj = new Regex(@"[^'d]");
resultString = regexObj.Replace(inputString, "");
return resultString;
}