我正在创建一个windows窗体应用程序,我遇到了一个问题。我正在从串口读取数据。
string RxString = serialPort1.ReadExisting();
这工作得很好,但我现在想做的是从我的RxString
提取值,并把它们放入自己的字符串数组。
这是RxString格式:
GPS:050.1347,N,00007.3612,WMAG:+231rn
当从串行端口添加更多数据时,它会重复自己,数字会改变但保持相同的长度,并且+变为-。我想把GPS:和N之间的数字放入一个字符串数组,N和W之间的数字放入另一个字符串数组,最后+和r N之间的数字放入第三个字符串数组。
我该怎么做呢?
Ok, Regex解:
string pattern = @"^GPS:(?<gps>.{8}),N,(?<n>.{10}),WMAG:(+|-)(?<wmag>.{3})\r\n$";
string gps = string.Empty;
string n = string.Empty;
string wmag = string.Empty;
string input = @"GPS:050.1347,N,00007.3612,WMAG:+231rn";
Regex regex = new Regex(pattern);
if (regex.IsMatch(input))
{
Match match = regex.Match(input);
foreach (Capture capture in match.Groups["gps"].Captures)
gps = capture.Value;
foreach (Capture capture in match.Groups["n"].Captures)
n = capture.Value;
foreach (Capture capture in match.Groups["wmag"].Captures)
wmag = capture.Value;
}
Console.Write("GPS: ");
Console.WriteLine(gps);
Console.Write("N: ");
Console.WriteLine(n);
Console.Write("WMAG: ");
Console.WriteLine(wmag);
Console.ReadLine();
试试这个:
string RxString = serialPort1.ReadExisting();
string latitude = RxString.Split(',')[0].Substring(4);
string longitude = RxString.Split(',')[2];
string mag = RxString.Split(',')[3].Substring(6).Trim();
如果字符串总是相同的长度,最好的方法是使用substring()
方法
我确信有一些正则表达式可以使这个更漂亮,但我不擅长正则表达式,所以我检查c#的字符串。分割函数。如果您知道数字的长度相同,则子字符串可以工作,但如果这不能保证,Split将是您最好的选择。您可以用逗号分隔每一行,创建一个数组,然后使用Replace删除额外的文本(如GPS:和WMAG:),如果您知道每次都是相同的。
这不是最好的解决方案,因为它使用了"魔术"数字和子字符串-但可能适合您的情况,因为您说字符串长度总是相同的。
var serialPortInfo = "GPS:050.1347,N,00007.3612,WMAG:+231rn";
private List<string> value1 = new List<string>();
private List<string> value2 = new List<string>();
private List<string> value3 = new List<string>();
private void populateValues(string s)
{
// this should give an array of the following:
// values[0] = "050.1347"
// values[1] = "N"
// values[2] = "00007.3612"
// values[3] = "WMAG:+231"
//
var values = (s.Substring(4, (s.Length - 8))).Split(',');
// populate lists
//
value1.Add(values[0]);
value2.Add(values[2]);
value3.Add(values[3].Substring(6, 3));
}
//usage
populateValues(serialPortInfo);