我正在创建一个 Windows 窗体应用程序,但遇到了一个问题。我正在从串行端口读取数据。
string RxString = serialPort1.ReadExisting();
这工作正常,但我现在想做的是从我的 RxString 中提取值并将它们放入它们自己的字符串数组中。
这是 RxString 格式:
GPS:050.1347,N,00007.3612,WMAG:+231\r\n
随着从串行端口添加更多数据,数字会发生变化但长度保持不变,并且 + 变为 -。我想将 GPS: 和 ,N 之间的数字放入一个字符串数组中,将 N 和 ,W 之间的数字放入另一个字符串数组中,最后将 + 和\r\n 之间的数字放入第三个字符串数组中。
我该怎么做?
请您参考如下方法:
好的,正则表达式解决方案:
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:+231\r\n";
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();
