我有一个GPS设备,每1秒输出一个单独的字符串,就像这样(几秒钟的数据):
$GPGGA,021225.000,5425.7163,N,01341.7347,E,1,14,0.73,-5.2,M,41.5,M,,*44
$GNRMC,021225.000,A,5425.7163,N,01341.7347,E,0.00,324.63,041017,,,A*70
$GPVTG,324.63,T,,M,0.00,N,0.00,K,A*3D
$GPGGA,021226.000,5425.7163,N,01341.7347,E,1,14,0.73,-5.2,M,41.5,M,,*47
$GNRMC,021226.000,A,5425.7163,N,01341.7347,E,0.00,324.63,041017,,,A*73
$GPVTG,324.63,T,,M,0.00,N,0.00,K,A*3D
$GPGGA,021227.000,5425.7163,N,01341.7347,E,1,14,0.73,-5.2,M,41.5,M,,*46
$GNRMC,021227.000,A,5425.7163,N,01341.7347,E,0.00,324.63,041017,,,A*72
$GPVTG,324.63,T,,M,0.00,N,0.00,K,A*3D
我的目标很简单,我只需要以$ GPGGA开头的(整个)字符串。相反,看到以上所有字符串,我只需要:
$GPGGA,021225.000,5425.7163,N,01341.7347,E,1,14,0.73,-5.2,M,41.5,M,,*44
$GPGGA,021226.000,5425.7163,N,01341.7347,E,1,14,0.73,-5.2,M,41.5,M,,*47
$GPGGA,021227.000,5425.7163,N,01341.7347,E,1,14,0.73,-5.2,M,41.5,M,,*46
简单,对吧?!
供参考,这是我正在使用的代码:
string numbers = Encoding.ASCII.GetString(e.Data);
var ismatch = Regex.Match(numbers, @"");
if (ismatch.Success)
{
tbData.AppendText(numbers);
}
else
{
tbData.AppendText("Invalid");
}
我很确定代码工作正常,因为@""它返回所有字符串(在UI的文本框中),而不显示“无效”字符串。代替。
我尝试了一百万种不同的表达方式,包括非常简单的表达式,但我无法掌握该语言。
那么对于那里的正则表达式天才,你能不能告诉我什么表达将适用于' $ GPGGA .......' ?
答案 0 :(得分:1)
$
是RegEx中的特殊字符。您需要将其转义以匹配它(\$
)。
所以这样的事情应该有效:
var ismatch = Regex.Match(numbers, @"^(\$GPGGA,.*)$", RegexOptions.Multiline);
让我们打破这个:
^
- 匹配输入的开头(
- 启动捕获组\$GPGGA,
- 匹配此特定文字(请注意转义的$).*
- 匹配其他所有内容)
- 捕获组的结束$
- 输入结束为了获得以$ GPGGA开头的每一行的捕获组,我必须启用Multiline(RegexOptions.Multiline
)。
仅供参考,我经常使用this site来测试正则表达式。他们的参考页面也很有帮助。
我为你准备了fiddle。
答案 1 :(得分:0)
答案不使用Rengex,但它有效,并花了一段时间确保它不包含任何错误。
//assume you have your string from Serial Port (COM)
string[] strArr = data.Split('$'); //split different GPS string
for (int j = 0; j < strArr.Length; j++)
{
string strTemp = strArr[j];
debug = strTemp;
string[] lineArr = strTemp.Split(',');
if (lineArr[0] == "GPGGA")
{
try
{
//Latitude
if (lineArr.Length >= 7 && lineArr[2] != "")
{
//Latitude
double converted = Convert.ToDouble(lineArr[2]) / 100;
string[] lat = converted.ToString().Split('.');
string altered = lat[1] + "000000000000000000000000";
double me = Convert.ToDouble(lat[0].ToString()) + ((Convert.ToDouble(altered.Substring(0, 6)) / 60)) / 10000;
Latitude = lineArr[3].ToString() + me.ToString();
//Longitude
double converted1 = Convert.ToDouble(lineArr[4]) / 100;
string[] lon = converted.ToString().Split('.');
string altered1 = lon[1] + "000000000000000000000000";
double me1 = Convert.ToDouble(lon[0].ToString()) + ((Convert.ToDouble(altered1.Substring(0, 6)) / 60)) / 10000;
Longitude = lineArr[5].ToString() + me1.ToString();
//Time
string timeMinAndSec = lineArr[1][0].ToString() + lineArr[1][1].ToString();
//Altitude
if (lineArr.Length >= 10)
{
Altitude = lineArr[9].ToString();
}
}
}
}
}