Parsing string to array using Regex in c# -
im making c# application receives string serialport, , need parse data can stuff it.
the strings send through serialport
formatted this:
*ntf,ctrl,sql,open,+,-66*ntf,ctrl,dbusy,on,+,-63*ntf,ctrl,dbusy,off*ntf,ctrl,sql,close*
now im wondering how can split string segments on *
symbol, have made couple attempts @ myself couldnt figure out.
the attempts made are:
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"; } }
which gave me:
ntf,ctrl,sql,open,+,-66 ntf,ct rl,dbusy ,on,+,-6 3 ntf,ct rl,dbusy ,off ntf,ct rl,sql,c lose
i have tried:
var regex = new regex('*'+".+"+'*'); var matches = regex.matches(data);
but gave me error.
what want achieve:
the formatted string this:
ntf,ctrl,sql,open,+,-66 ntf,ctrl,dbusy,on,+,-63 ntf,ctrl,dbusy,off ntf,ctrl,sql,close
edit:
i have solved problem having 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 said "preferrably regex" cleaner imho 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 remember string.split
is string begins or ends delimiter you'll empty entries @ beginning , end, respectively, of resulting array. adding stringsplitoptions.removeemptyentries
parameter removes empty entries left 2 stings between each pair of asterisks.
Comments
Post a Comment