im currently making an c# application that receives a string from an serialport, and i need to parse this data so i can do stuff with it.
The strings that are send through the SerialPort
are formatted like this:
*NTF,CTRL,SQL,OPEN,+,-66*NTF,CTRL,DBUSY,ON,+,-63*NTF,CTRL,DBUSY,OFF*NTF,CTRL,SQL,CLOSE*
now im wondering how i can split this string into segments on the *
symbol,
i have made a couple attempts at this myself but couldnt figure it out.
String[] tmp = data.ToString().Split('*');
foreach(String word in tmp)
{
if (word.Contains(",80") || word.Contains(",81"))
{
COM_PORT_INFO_BOX.Text += word + "\r\n";
}
}
NTF,CTRL,SQL,OPEN,+,-66
NTF,CT RL,DBUSY
,ON,+,-6
3
NTF,CT
RL,DBUSY
,OFF NTF,CT
RL,SQL,C
LOSE
var regex = new Regex('*'+".+"+'*');
var matches = regex.Matches(data);
But this gave me an error.
NTF,CTRL,SQL,OPEN,+,-66
NTF,CTRL,DBUSY,ON,+,-63
NTF,CTRL,DBUSY,OFF
NTF,CTRL,SQL,CLOSE
I have solved the problem by having this piece of code:
SerialPort sp = (SerialPort)sender;
data += sp.ReadExisting().ToString();
string[] tmp = data.Split(new char[] {'\u0002','\u0003'}, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in tmp)
{
if (line.Contains(",80") || line.Contains(",81") || line.Contains(",RXVCALL"))
{
COM_PORT_INFO_BOX.Text += line.Substring(1) + "\r\n";
data = "";
}
}
I know you said "preferrably with regex" but this is cleaner IMHO with String.Split
:
string s = "*blablablab,blablabla,blablabla,blablabla*blablabla,blabalbal,blablabla*";
string[] results = s.Split(new [] {'*'}, StringSplitOptions.RemoveEmptyEntries);
results:
String[] (2 items)
----------------------------
blablablab,blablabla,blablabla,blablabla
blablabla,blabalbal,blablabla
One thing to remember with String.Split
is that is your string begins or ends with a delimiter you'll get empty entries at the beginning and end, respectively, of the resulting array. Adding the StringSplitOptions.RemoveEmptyEntries
parameter removes those empty entries so you are just left with the two stings between each pair of asterisks.